# dfs模版题：力扣79单词搜索

class Solution {
boolean res = false;
boolean[][] visited;
int m;
int n;
public boolean exist(char[][] board, String word) {
m = board.length;
n = board[0].length;
visited = new boolean[m][n];//默认是false,表示这条路没有被走过
//现在首先先找到第一个字符
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(!visited[i][j] && board[i][j] == word.charAt(0)){
dfs(i,j,1,word,board);
}
}
}
return res;
}
public void dfs(int i,int j,int count,String word,char[][]board){
if(count == word.length()){
res = true;
return;
}
//先设置标志
visited[i][j] = true;
//上 下 左 右
if(res == false  && i-1>=0 && board[i-1][j] == word.charAt(count)&&!visited[i-1][j]){//相等在走（加）,这边的count其实是上次加的，代比较的新位置
dfs(i-1,j,count+1,word,board);
}
if(res ==false  && i+1<m && board[i+1][j] == word.charAt(count)&& !visited[i+1][j]){
dfs(i+1,j,count+1,word,board);
}
if(res == false && j-1>=0 && board[i][j-1] == word.charAt(count) && !visited[i][j-1]){
dfs(i,j-1,count+1,word,board);
}
if(res == false  && j+1<n && board[i][j+1] == word.charAt(count)&&!visited[i][j+1]){
dfs(i,j+1,count+1,word,board);
}
//回溯的时候,恢复
visited[i][j] = false;
}
}

11-13
02-04 269

02-28
07-12 416
05-03 44
08-22 24
©️2020 CSDN 皮肤主题: 游动-白 设计师:上身试试