
public class Main {
public int[][] visit;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str){
visit = new int[rows][cols];
char[][] array = new char[rows][cols];
for (int i = 0;i<rows;i++) {
for (int j = 0;j<cols;j++) {
array[i][j] = matrix[i*cols+j];
}
}
for (int i = 0;i<rows;i++) {
for (int j = 0;j<cols;j++) {
if (find(array,rows,cols,str,i,j,0)) {
return true;
}
}
}
return false;
}
private boolean find(char[][] array, int rows, int cols, char[] str, int i, int j, int index) {
if (index>=str.length) {
return true;
}
if (i<0||j<0||i>=rows||j>=cols||array[i][j]!=str[index]||visit[i][j] == 1) {
return false;
}
visit[i][j] = 1;
boolean isSunc = find(array,rows,cols,str,i+1,j,index+1)
||find(array,rows,cols,str,i,j+1,index+1)
||find(array,rows,cols,str,i-1,j,index+1)
||find(array,rows,cols,str,i,j-1,index+1);
visit[i][j] = 0;
return isSunc;
}
}