請設計1個函數,用來判斷在1個矩陣中是不是存在1條包括某字符串所有字符的路徑。路徑可以從矩陣中的任意1個格子開始,每步可以在矩陣中向左,向右,向上,向下移動1個格子。如果1條路徑經過了矩陣中的某1個格子,則該路徑不能再進入該格子
深度搜索
public class Solution {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
if(matrix.length == 1 && str.length ==1 && matrix[0] == str[0])
return true;
char[][] mat = new char[rows][cols];
for(int i = 0;i<rows;i++){
for(int j =0;j<cols;j++){
mat[i][j] = matrix[i*cols+j];
}
}
for(int i = 0;i<rows;i++){
for(int j =0;j<cols;j++){
boolean[][] visited = new boolean[rows][cols];
boolean res = dfs(mat,i,j,0,str,visited);
if(res)
return true;
}
}
return false;
}
public boolean dfs(char[][] mat,int i,int j,int id,char[] str,boolean[][] visited){
if(i<0 || i>=mat.length||j<0||j>=mat[0].length || id<0||id>str.length)
return false;
if(id == str.length)
return true;
if(!visited[i][j] && mat[i][j] == str[id]){
visited[i][j] = true;
boolean res = dfs(mat,i,j+1,id+1,str,visited)||
dfs(mat,i,j-1,id+1,str,visited)||
dfs(mat,i-1,j,id+1,str,visited)||
dfs(mat,i+1,j,id+1,str,visited);
visited[i][j] = false;
return res;
}
return false;
}
}