dfs模板题
class Solution {
public boolean hasPath(char[][] matrix, String str) {
if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
return false;
}
int row = matrix.length;
int col = matrix[0].length;
boolean[][] visited = new boolean[row][col];
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(dfs(matrix,str,0,i,j,visited)){
return true;
}
}
}
return false;
}
private boolean dfs(char[][] m,String s,int idx, int i, int j, boolean[][] visited){
if(idx == s.length()){
return true;
}
if(i < 0 || i >= m.length || j < 0 || j >= m[0].length || visited[i][j] || m[i][j] != s.charAt(idx)){
return false;
}
int[][] dirs = {{-1,0},{0,1},{1,0},{0,-1}};
visited[i][j] = true;
for(int[] dir : dirs){
if(dfs(m,s,idx+1,dir[0] + i,dir[1] + j,visited)){
return true;
}
}
visited[i][j] = false;
return false;
}
}