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

    }

  • 相关阅读:
    自定义标签
    ssm学习的第一个demo---crm(1)
    xml文件中的${}
    Mybatis的回顾学习
    Mapper的.xml文件的delete的参数问题
    mybatis中xml文件的${}和#{}区别
    Mybatis:通过MapperScannerConfigurer进行mapper扫描
    Spring的applicationContext.xml的疑问解析
    Spring MVC 的springMVC.xml疑问解析
    【剑指 Offer】04.二维数组中的查找
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12444168.html
Copyright © 2020-2023  润新知