题目描述:
思路:很典型的深度优先+回溯。题解中对于方向的解决方法十分巧妙。使用了二维数组来代表方向选择,避免了自己写很多的重复代码。
class Solution {
public boolean exist(char[][] board, String word) {
int m=board.length;
int n=board[0].length;
boolean [][] visited=new boolean[m][n];
char[] words=word.toCharArray();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
boolean flag=isExist(i,j,board,words,0,visited);
if(flag) return true;
}
}
return false;
}
private boolean isExist(int i,int j,char[][] board,char[] words,int s,boolean[][] visited){
if(board[i][j]!=words[s]){
return false;
}else if(s==words.length-1){
return true;
}
visited[i][j]=true;
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
boolean result = false;
for (int[] dir : directions) {
int newi = i + dir[0], newj = j + dir[1];
if (newi >= 0 && newi < board.length && newj >= 0 && newj < board[0].length) {
if (!visited[newi][newj]) {
boolean flag = isExist(newi, newj, board,words, s+1, visited);
if (flag) {
result = true;
break;
}
}
}
}
visited[i][j] = false;
return result;
}
}