回溯法
打个卡
class Solution {
private int[] dx = {1, -1, 0, 0};
private int[] dy = {0, 0, 1, -1};
private boolean[][] visited;
public boolean hasPath(char[][] matrix, String str) {
if(str.length() == 0)return true;
if(matrix.length == 0 || matrix[0].length == 0)return false;
int r = matrix.length, c = matrix[0].length;
visited = new boolean[r][c];
for(int i = 0; i < r; i ++)
for(int j = 0; j < c; j ++)
visited[i][j] = false;
for(int i = 0; i < r; i ++)
for(int j = 0; j < c; j ++){
if(matrix[i][j] == str.charAt(0)){
visited[i][j] = true;
boolean res = dfs(matrix, str, 1, i, j);
visited[i][j] = false;
if(res)return true;
}
}
return false;
}
private boolean dfs(char[][] matrix, String str, int curPos, int x, int y){
if(curPos == str.length())return true;
int r = matrix.length, c = matrix[0].length;
boolean res = false;
for(int i = 0; i < 4; i ++){
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < r && b >= 0 && b < c && !visited[a][b] && matrix[a][b] == str.charAt(curPos)){
visited[a][b] = true;
res = res || dfs(matrix, str, curPos + 1, a, b);
visited[a][b] = false;
}
}
return res;
}
}