import org.junit.Test;
public class solution {
@Test
public void testFunc(){
char[][] matrix = {
{'a','b','t','g'},
{'c','f','c','s'},
{'j','d','e','h'},
};
String string="bfce";
boolean res = hasPath(matrix, string);
System.out.println("res: "+res);
}
int[][] direc = {{0,-1},{0,1},{-1,0},{1,0}};
boolean[][] memo;
// 矩阵中的路径:判断矩阵中是否存在某个字符串路径
public boolean hasPath(char[][] matrix, String str){
char[] charArr = str.toCharArray();
memo=new boolean[matrix.length][matrix[0].length];
for(int i=0;i<matrix.length;i++){
for(int j=0;j<matrix[0].length;j++){
if (hasPath2(matrix, i,j,charArr,0)) {
return true;
}
}
}
return false;
}
//判断从某个顶点开始是否存在路径
private boolean hasPath2(char[][] matrix,int i,int j, char[] charArr,int index) {
if (index==charArr.length) {
return true;
}
if (matrix[i][j]!=charArr[index]) {
return false;
}
memo[i][j]=true;
for(int d=0;d<direc.length;d++){
int row = i+direc[d][0];
int col = j+direc[d][1];
if (row>=0 && col>=0 && !memo[row][col]) {
if (hasPath2(matrix, row, col, charArr, index+1)) {
return true;
}
}
}
memo[i][j]=false;
return false;
}
}