public class Solution {
char[] matrix;
char[] str;
int rows;
int cols;
int pathLength = 0;
boolean[] visited;
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
if(matrix==null || matrix.length==0 || str==null || str.length==0)
return false ;
this.matrix = matrix;
this.str = str;
this.rows = rows;
this.cols = cols;
visited = new boolean[rows*cols] ;
for(int i=0 ; i<rows ; i++) {
for(int j=0 ; j<cols ; j++) {
if(hasPathCore(i, j))
return true;
}
}
return false;
}
public boolean hasPathCore(int row, int col) {
if(pathLength==str.length)
return true;
boolean hasPath = false;
if(row>=0 && row<rows && col>=0 && col<cols
&& matrix[row*cols+col] == str[pathLength]
&& !visited[row*cols+col]){
pathLength++;
visited[row*cols+col] = true;
hasPath = (hasPathCore(row-1, col)
||hasPathCore(row, col+1)
||hasPathCore(row+1, col)
||hasPathCore(row, col-1));
if(!hasPath){
pathLength--;
visited[row*cols+col] = false;
}
}
return hasPath;
}
}
定义了许多全局变量,简便了过程。(要注意row>=0 && row<rows && col>=0 && col<cols,在这里错了好多次才通过)