LeetCode-079-单词搜索
思路
回溯法,向四个方向进行遍历,注意判断边界条件
代码
class Solution {
boolean [][]v;
char [][]board;
int[][] dir = {{-1, 0}, {0, -1}, {0, 1}, {1, 0}};
char[] charArray;
int rows;
int cols;
int len;
public boolean exist(char[][] board, String word) {
rows=board.length;
if(rows==0)return false;
cols=board[0].length;
len=word.length();
charArray=word.toCharArray();
v=new boolean[rows][cols];
this.board=board;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if (dfs(i,j,0)) {
return true;
}
}
}
return false;
}
boolean dfs(int i,int j,int index){
if(index==len-1)return charArray[index]==board[i][j];
if(charArray[index]==board[i][j]){
v[i][j]=true;
for(int []d:dir){
int x=i+d[0];
int y=j+d[1];
if(check(x,y)&&!v[x][y]){
if (dfs(x,y,index+1)) {
return true;
}
}
}
v[i][j]=false;
}
return false;
}
boolean check(int x,int y){
return x>=0&&x<rows&&y>=0&&y<cols;
}
}