zoukankan      html  css  js  c++  java
  • 剑指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();
    }

    }

  • 相关阅读:
    关于配置文件权衡,.config VS .xml
    Google不支持小于12px字体 终极办法
    两个表循环的复杂度分析 征集
    SQL 计算列
    5分钟上手写ECharts的第一个图表
    NGif, Animated GIF Encoder for .NET
    Chart系列(一):Chart的基本元素
    一张广告图片引起的思维DFS
    洛谷 P2580 于是他错误的点名开始了
    洛谷 P1496 火烧赤壁
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12444168.html
Copyright © 2011-2022 走看看