剑指Offer(Java版)第十一题

public class Class112 {
public boolean findPath(char[] matrix, int rows, int cols, char[] str){
boolean anchor[] = new boolean[matrix.length];
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
int count = 0;
if(findPathMain(matrix, row, col, rows, cols, str, count, anchor)){
return true;
}
}
}
return false;
}
public boolean findPathMain(char[] matrix, int row, int col, int rows, int cols, char[] str, int count, boolean[] anchor){
int index = row * cols + col;
if(row < 0 || row >= rows || col < 0 || col >= cols || matrix[index] != str[count] || anchor[index] == true){
return false;
}
if(count == str.length - 1){
return true;
}
anchor[index] = true;

if(findPathMain(matrix,row,col-1,rows,cols,str,count+1,anchor)
||findPathMain(matrix,row,col+1,rows,cols,str,count+1,anchor)
||findPathMain(matrix,row-1,col,rows,cols,str,count+1,anchor)
||findPathMain(matrix,row+1,col,rows,cols,str,count+1,anchor)){
return true;
}
anchor[index] = false;
return false;
}


public void test1() {
char[] matrix = "ABTGCFCSJDEH".toCharArray();
int rows = 3;
int cols = 4;
char[] str = "abfb".toCharArray();
if (!findPath(matrix, rows, cols, str))
System.out.println("Test1 passed.");
else
System.out.println("Test1 failed.");
}
public void test2() {
char[] matrix = "ABTGCFCSJDEH".toCharArray();
int rows = 3;
int cols = 4;
char[] str = "ABFB".toCharArray();
if (!findPath(matrix, rows, cols, str))
System.out.println("Test2 passed.");
else
System.out.println("Test2 failed.");
}

public static void main(String[] args) {
// TODO Auto-generated method stub
Class11 c = new Class11();
c.test1();
c.test2();
}

}

原文地址:https://www.cnblogs.com/zhuozige/p/12444168.html