思路
题目是在一个图中找到指定字符串,而图的大小m,n都是小于等于6,完全能用暴力的方式求解,可以考虑经典的迷宫问题,出发点到迷宫出口的路径就是一个字符串,而迷宫问题的解法就是dfs,此题只需要遍历全部起点,运用dfs算法即可得出解
class Solution {
public boolean exist(char[][] board, String word) {
//上下左右移动
int[][] d = {{1,0},{-1,0},{0,1},{0,-1}};
//打标记,走过的就不能再走,注意回溯
Boolean[][] book = new Boolean[10][10];
Boolean s = false;
//遍历起点
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
//初始化标记
for (int k = 0; k < 10; k++) {
for (int m = 0; m < 10; m++) {
book[k][m] = false;
}
}
s= dfs(i,j,0,0,board,word,"",d, book);
if (s){
return s;
}
}
}
return s;
}
public Boolean dfs(int dx, int dy, int x, int y, char[][] board, String word, String s, int[][] d, Boolean[][] book){
x += dx;
y += dy;
//判断是否越界,以及是否已经走过
if (x<0|| y<0 || x >= board.length || y >= board[x].length || book[x][y]){
return false;
}
book[x][y] = true;
s += board[x][y];
//剪枝,不知道为啥,按道理数据量很小,但不剪枝超时,搞不懂
if(s.length() > word.length()){
//注意此处需要回溯
book[x][y] = false;
return false;
}
if (word.equals(s)){
return true;
}
//dfs遍历
for (int i = 0; i < 4; i++) {
if (dfs(d[i][0], d[i][1], x, y, board, word, s,d, book)){
return true;
}
}
//回溯
book[x][y] = false;
return false;
}
}