Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ['A','B','C','E'], ['S','F','C','S'], ['A','D','E','E'] ]word =
"ABCCED"
,
-> returns true
,word =
"SEE"
,
-> returns true
,word =
"ABCB"
,
-> returns false
.
public class Solution {
public boolean exist(char[][] board, String word) {
char[] wordlist = word.toCharArray();
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(helper(board, i ,j , wordlist, 0 )){
return true;
}
}
}
return false;
}
private boolean helper(char[][] board, int i, int j , char[] word, int index){
if(index == word.length){
return true;
}
if(i < 0 || j < 0 || i > board.length - 1 || j > board[0].length - 1 || index > word.length - 1){
return false;
}
if(board[i][j] != word[index]){
return false;
}
board[i][j] ^= 256;//这里参考了网上的思路 很神奇 把char变成无效的
boolean result = helper(board, i + 1, j , word, index + 1) ||
helper(board, i , j + 1, word, index + 1)||
helper(board, i - 1, j , word, index + 1)||
helper(board, i, j - 1 , word, index + 1);
board[i][j] ^= 256;
return result;
}
}