深度优先
class Solution {
public boolean exist(char[][] board, String word) {
char[] words = word.toCharArray();
int m = words.length;
boolean[][] visit = new boolean[board.length][board[0].length];
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j] == words[0]){//找到起始位置
if(dfs(i,j,visit,0,board,words)) return true;
}
}
}
return false;
}
private boolean dfs(int i,int j,boolean[][]visit, int index,char[][]board,char[] words){
if(index == words.length) return true;
if(i < 0 || i >= board.length || j < 0 || j >= board[0].length
|| board[i][j] != words[index] || visit[i][j]){
return false;
}
visit[i][j] = true;
boolean flag = dfs(i+1,j,visit,index+1,board,words)//四个方向尝试
||dfs(i,j+1,visit,index+1,board,words)
||dfs(i-1,j,visit,index+1,board,words)
||dfs(i,j-1,visit,index+1,board,words);
visit[i][j] = false;
return flag;
}
}