题解
- dfs ,对棋盘里的每个点都dfs一遍,看是否有合适的字符串。
- 当找到最后一个字符位置,并且最后一个字符,并且当前字符串匹配,那么为真。
- 注意回溯之后的标记需要改成false , 因为需要回溯进行查找。
class Solution {
public static boolean vis[][] = new boolean[8][8];
public static int dir[] = {-1,0,1,0,-1};
public static boolean ans;
public static void dfs(char[][] board, String word, int x, int y, int n ){
// System.out.println("n: " + n);
if(n == word.length() -1 && board[x][y] == word.charAt(n) ){
ans = true;
return;
}
for(int i = 0; i < 4; i++){
int dx = x + dir[i];
int dy = y + dir[i+1];
// System.out.println(dx + " " + dy);
if(dx >= 0 && dx < board.length && dy >=0 && dy < board[0].length && !vis[dx][dy] && board[x][y] == word.charAt(n)) {
vis[dx][dy] = true;
// System.out.println(word.charAt(n) + " " + n);
// System.out.println(x + " " + y);
// System.out.println("d " + dx + " " + dy);
dfs(board, word, dx, dy, (n + 1));
vis[dx][dy] = false;
}
}
}
public boolean exist(char[][] board, String word) {
ans = false;
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(word.length() == 1 && board[i][j] == word.charAt(0)){
ans = true;
}
else if(board[i][j] == word.charAt(0)) {
vis[i][j] = true;
dfs(board, word, i, j, 0);
vis[i][j] = false;
}
}
}
// System.out.println(ans);
return ans;
// System.out.println();
}
}