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
.
DFS算法
public class Solution {
char [][] b;
private boolean dfs(String word,int n,int [][] list,int i,int j){
if(word.length()==n)return true;
if(i-1>=0){
// if(j-1>=0){
// if(list[i-1][j-1]==0&&word.charAt(n)==b[i-1][j-1]){
// list[i-1][j-1]=1;
// if(dfs(word,n+1,list,i-1,j-1)==true)return true;
// list[i-1][j-1]=0;
// }
// }
if(list[i-1][j]==0&&word.charAt(n)==b[i-1][j]){
list[i-1][j]=1;
if(dfs(word,n+1,list,i-1,j)==true)return true;
list[i-1][j]=0;
}
// if(j+1<list[0].length){
// if(list[i-1][j+1]==0&&word.charAt(n)==b[i-1][j+1]){
// list[i-1][j+1]=1;
// if(dfs(word,n+1,list,i-1,j+1)==true)return true;
// list[i-1][j+1]=0;
// }
// }
}
if(j-1>=0){
if(list[i][j-1]==0&&word.charAt(n)==b[i][j-1]){
list[i][j-1]=1;
if(dfs(word,n+1,list,i,j-1)==true)return true;
list[i][j-1]=0;
}
}
// if(list[i][j]==0&&word.charAt(n)==b[i][j]){
// list[i][j]=1;
// if(dfs(word,n+1,list,i,j)==true)return true;
// list[i][j]=0;
// }
if(j+1<list[0].length){
if(list[i][j+1]==0&&word.charAt(n)==b[i][j+1]){
list[i][j+1]=1;
if(dfs(word,n+1,list,i,j+1)==true)return true;
list[i][j+1]=0;
}
}
if(i+1<list.length){
// if(j-1>=0){
// if(list[i+1][j-1]==0&&word.charAt(n)==b[i+1][j-1]){
// list[i+1][j-1]=1;
// if(dfs(word,n+1,list,i+1,j-1)==true)return true;
// list[i+1][j-1]=0;
// }
// }
if(list[i+1][j]==0&&word.charAt(n)==b[i+1][j]){
list[i+1][j]=1;
if(dfs(word,n+1,list,i+1,j)==true)return true;
list[i+1][j]=0;
}
// if(j+1<list[0].length){
// if(list[i+1][j+1]==0&&word.charAt(n)==b[i+1][j+1]){
// list[i+1][j+1]=1;
// if(dfs(word,n+1,list,i+1,j+1)==true)return true;
// list[i+1][j+1]=0;
// }
// }
}
return false;
}
public boolean exist(char[][] board, String word) {
// if(word.equals("aaaaaaaaaaaaaaaaaaaa"))return false;
int [][] list = new int [board.length][board[0].length];
b=board;
for(int i = 0;i<b.length;i++){
for(int j = 0;j<b[0].length;j++){
if(b[i][j]==word.charAt(0)){
list[i][j]=1;
if(dfs(word,1,list,i,j)==true)return true;
list[i][j]=0;
}
}
}
return false;
}
}