题目:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
此题目仍是上下左右进行搜索:直接上代码:
package bineryTreePre;
public class MatrixPath {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{
Boolean flag[]=new Boolean[matrix.length];
for(int i=0;i<matrix.length;i++){
flag[i]=false;
}
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
if(hasingPath(matrix, rows, cols, str, 0, i, j, flag)){
return true;
}
}
}
return false;
}
public boolean hasingPath(char[] matrix, int rows, int cols, char[] str, int k,int i, int j, Boolean[]flag) {
int index=i*cols+j;
if(i<0||i>=rows||j<0||j>=cols||matrix[index]!=str[k]||flag[index]){
return false;
}
if(k==str.length-1)
return true;
flag[index]=true;
if(hasingPath(matrix, rows, cols, str, k+1, i+1, j, flag)||
hasingPath(matrix, rows, cols, str, k+1, i-1, j, flag)||
hasingPath(matrix, rows, cols, str, k+1, i, j+1, flag)||
hasingPath(matrix, rows, cols, str, k+1, i, j-1, flag)){
return true;
}
return false;
}
public static void main(String[] args) {
String matrix="abcesfcsadee";
String str="bcced";
System.out.println(new MatrixPath().hasPath(matrix.toCharArray(), 3, 4, str.toCharArray()));
}
}
尽管java中的Boolean数组默认为false,但是我们最好还是初始化一下。然后进行遍历搜索,每一个都作为顶点进行匹配,然后上下左右进行匹配,flag数组判断此坐标下是否已经遍历。