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

    }

  • 相关阅读:
    洛谷 P1291 [SHOI2002]百事世界杯之旅 解题报告
    洛谷 P1338 末日的传说 解题报告
    洛谷 P3952 时间复杂度 解题报告
    vector-erase
    STL之--插入迭代器(back_inserter,inserter,front_inserter的区别
    STL之--插入迭代器(back_inserter,inserter,front_inserter的区别
    vector-end
    vector-end
    vector-empty
    vector-empty
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12444168.html
Copyright © 2011-2022 走看看