注意:找到一个word后要及时返回,不要再向更深层递归了,不然会超时。
每个单元格只是在一条dfs路径上不能被重复使用,所以要回溯还原visited数组。
class Solution {
//行数 列数
private int m;
private int n;
private int[][] visited;
private boolean flag = false;
public boolean exist(char[][] board, String word) {
m = board.length;
n = board[0].length;
visited = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(board[i][j] == word.charAt(0) && visited[i][j] != 1){
DFS(board, word, i, j, 1);
}
}
}
return flag;
}
//index是指单词的索引
public void DFS(char[][] board, String word, int i, int j, int index){
//深度出口
if(index == word.length()){
flag = true;
return;
}
visited[i][j] = 1;
if(flag == false){
//注意下标等于0
if(i - 1 >= 0 && board[i - 1][j] == word.charAt(index) && visited[i - 1][j] != 1)
DFS(board, word,i - 1, j, index + 1);
if(j -1 >= 0 && board[i ][j - 1] == word.charAt(index) && visited[i][j - 1] != 1)
DFS(board, word,i , j - 1, index + 1);
if(i + 1 < m && board[i + 1][j] == word.charAt(index) && visited[i + 1][j] != 1)
DFS(board, word,i + 1 , j, index + 1);
if(j +1 < n && board[i][j + 1] == word.charAt(index) && visited[i][j + 1] != 1)
DFS(board, word,i , j + 1 , index + 1);
}
visited[i][j] = 0;
}
}