//要求上下左右移动,去过的点不可再次去
//写了递归实现与循环实现
//递归
class Solution1 {
public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
//边界条件
if(matrix==null || matrix.length==0 || str==null || str.length==0 || matrix.length!=rows*cols || rows<=0 || cols<=0 || rows*cols < str.length) {
return false ;
}
//访问标志位
boolean[] visited = new boolean[rows*cols] ;
int[] pathLength = {0} ;
for(int i=0 ; i<=rows-1 ; i++) {
for(int j=0 ; j<=cols-1 ; j++) {
if(hasPathCore(matrix, rows, cols, str, i, j, visited, pathLength)) { return true ; }
}
}
return false ;
}
public boolean hasPathCore(char[] matrix, int rows, int cols, char[] str, int row, int col, boolean[] visited, int[] pathLength) {
boolean flag = false ;
if(row>=0 && row<rows && col>=0 && col<cols && !visited[row*cols+col] && matrix[row*cols+col]==str[pathLength[0]]) {
pathLength[0]++ ;
visited[row*cols+col] = true ;
if(pathLength[0]==str.length) { return true ; }
flag = hasPathCore(matrix, rows, cols, str, row, col+1, visited, pathLength) ||
hasPathCore(matrix, rows, cols, str, row+1, col, visited, pathLength) ||
hasPathCore(matrix, rows, cols, str, row, col-1, visited, pathLength) ||
hasPathCore(matrix, rows, cols, str, row-1, col, visited, pathLength) ;
if(!flag) {
pathLength[0]-- ;
visited[row*cols+col] = false ;
}
}
return flag ;
}
}
//循环实现
class Solution2{
public static boolean hasPath(char[] matrix, int rows, int cols, char[] str)
{ if(matrix==null||matrix.length<str.length)
return false;
int len = matrix.length;
boolean[] array = new boolean[len];
Arrays.fill(array, false);
int[] dirc = new int[len];
Arrays.fill(dirc, -1);
int r,c;
int index=1;
Stack<Integer> s = new Stack<Integer>();
for(int i =0; i<len;i++){
//找到首字母
Arrays.fill(array, false);
s = new Stack<Integer>();
Arrays.fill(dirc, -1);
if(matrix[i]==str[0]){
r = i/cols;
c = i%cols;
array[i]=true;
s.push(i);
//递归查找
//System.out.println(i);
if(str.length==1)
return true;
while(true){
//System.out.println(i);
int loc= r*cols+c;
if(++dirc[loc]<=3){
//上下左右
int oldR = r;
int oldC=c;
if(dirc[loc]==0){
r = r>=1?r-1:r;
if(array[r*cols+c]==true){
r=oldR;
}
}else
if(dirc[loc]==1){
r=r<(rows-1)?r+1:r;
if(array[r*cols+c]==true){
r=oldR;
}
}else
if(dirc[loc]==2){
c=c>=1?c-1:c;
if(array[r*cols+c]==true){
c=oldC;
}
}else
if(dirc[loc]==3){
c=c<(cols-1)?c+1:c;
if(array[r*cols+c]==true){
c=oldC;
}
}
//找到新的方向
if(r!=oldR||c!=oldC){
int locNew = r*cols+c;
//没被访问过
if(array[locNew]==false){
//相等
if(matrix[locNew]==str[index]){
index++;
System.out.println("weizhio"+i);
//System.out.println(locNew);
if(index==str.length)
return true;
s.push(locNew);
array[locNew]=true;//修改访问标志位
}//不相等则退回
else{
r = oldR;
c=oldC;
}
}
}
}else{
if(s.isEmpty()){
index=1;
break;
}
array[s.pop()]=false;//一处栈顶,修改访问位
index--;
if(s.size()>=1){
r = s.peek()/cols;
c = s.peek()%cols;
//System.out.printlnloc);
}
}
}
}
}
return false;
}
}
判断一个矩阵中是否可以找到一条包含某个String的路径
最新推荐文章于 2020-11-05 15:16:12 发布