請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則之后不能再次進入這個格子。 例如 a b c e s f c s a d e e 這樣的3 X 4 矩陣中包含一條字符串"bcced"的路徑,但是矩陣中不包含"abcb"路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。
public class Solution {
int flag[];
int rows ;
int cols;
boolean ok =false;
public boolean findPath(char[] matrix, int c, int r, char[] str,int k){
if(k==str.length){
return true;
}
if(r>=0&&c>=0&&r<rows&&c<cols
&&matrix[c*rows+r]==str[k]
&&flag[c*rows+r]==0){
flag[c*rows+r]=1;
if(findPath(matrix,c,r+1,str,k+1)
||findPath(matrix,c,r-1,str,k+1)
||findPath(matrix,c-1,r,str,k+1)
||findPath(matrix,c+1,r,str,k+1))
return true;
flag[c*rows+r]=0;
}
return false;
}
public boolean hasPath(char[] matrix, int cols, int rows, char[] str){
this.rows =rows;
this.cols =cols;
flag = new int[cols*rows];
for(int i=0;i<cols;i++){
for(int j=0;j<rows;j++){
if(findPath(matrix,i,j,str,0)) return true;
}
}
return false;
}
}