码迷,mamicode.com
首页 > 编程语言 > 详细

剑指Offer(Java版)第十一题

时间:2020-03-08 19:59:34      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:static   pass   public   har   class   generated   rate   new   off   

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();
}

}

剑指Offer(Java版)第十一题

标签:static   pass   public   har   class   generated   rate   new   off   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!