package swordToOffer;
public class Num11_PathInMatrix {
public static void main(String[] args) {
// TODO Auto-generated method stub
// A B T G
// C F C S
// J D E H
// BFCTB
char[] matrix = "ABTGCFCSJDEH".toCharArray();
int rows = 3;
int cols = 4;
char[] str = "BFCTB".toCharArray();
if (!hasPath(matrix, rows, cols, str))
System.out.println("Test passed.");
else
System.out.println("Test failed.");
}
public static boolean hasPath(char[] matrix,int rows,int cols,char[] str) {
if(matrix==null||rows<1||cols<1||str==null) {
return false;
}
boolean[] isVisited = new boolean[rows*cols];
for(boolean s: isVisited) {
s = false;
}
int pathLength = 0;
for(int row = 0;row<rows;row++) {
for(int col = 0;col<cols;col++) {
if(hasPathCore(matrix,rows,cols,row,col,str,pathLength,isVisited))
return true;
}
}
return false;
}
public static boolean hasPathCore(char[] matrix,int rows,int cols,int row,int col,char[] str,int pathLength,boolean[] isVisited) {
if(row<0||col<0||row>rows||col>cols||isVisited[row*cols+col]==true||str[pathLength]!=matrix[row*cols+col]) {
return false;
}
if(pathLength==str.length-1)
return true;
boolean hasPath = false;
isVisited[row*cols+col] = true;
hasPath = hasPathCore(matrix,rows,cols,row-1,col,str,pathLength+1,isVisited)
||hasPathCore(matrix,rows,cols,row+1,col,str,pathLength+1,isVisited)
||hasPathCore(matrix,rows,cols,row,col-1,str,pathLength+1,isVisited)
||hasPathCore(matrix,rows,cols,row,col+1,str,pathLength+1,isVisited);
if(!hasPath)
isVisited[row*cols+col] = false;
return hasPath;
}
}