剑指Offer——题12(矩阵中的路径)

【题目】:

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。 例如 a b c e s f c s a d e e 这样的3 X 4 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

a    b    c    e

s    f     c     s

a    d    e    e

【思路】:

首先对所整个矩阵遍历,找到第一个字符,然后向上下左右查找下一个字符,由于每个字符都是相同的判断方法(先判断当前字符是否相等,再向四周查找),因此采用递归函数。由于字符查找过后不能重复进入,所以还要定义一个与字符矩阵大小相同的布尔值矩阵,进入过的格子标记为true。如果不满足的情况下,需要进行回溯,此时,要将当前位置的布尔值标记回false。(所谓的回溯无非就是对使用过的字符进行标记和处理后的去标记)

java code:

package com.offer.offer12;

/**
 * @author zth
 * @Date 2019-08-08 17:29
 */
public class StringPathInMatrix  {
    /**
     * 判断是否包含路径
     * @param matrix 字符矩阵
     * @param rows 矩阵的行数
     * @param cols 矩阵的列数
     * @param str 待查找的字符数组
     * @return 找到返回 true,否则返回 false
     */
    public boolean hasPath(char[] matrix,int rows,int cols,char[] str){
        if (null == matrix || rows<1 || cols < 1 || null == str){
            return false;
        }
        // 记录是否已经移入每个格子
        boolean[] isVisited = new boolean[rows * cols];
        for (int i = 0; i < isVisited.length; i++) {
            isVisited[i] = false;
        }

        // 记录当前已经查找字符串的长度
        int pathLength = 0;

        // 每一个格子可以作为起点进行查找
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                if (hasPathCore(matrix,rows,cols,row,col,str,pathLength,isVisited))
                    return true;
            }
        }
        return false;
    }

    private boolean hasPathCore(char[] matrix,int rows,int cols,int row, int col,
                                char[] str,int pathLength, boolean[] isVisited){

        if (row<0 || col <0 || row>=rows || col>=cols ||  // 范围不正确
                isVisited[row * cols+col]==true ||      // 当前小格已访问过
                str[pathLength] != matrix[row * cols+col]   // 字符不相等
        )return false;

        if (pathLength == str.length-1){
            return true;
        }

        isVisited[row * cols +col] = true;
         boolean hasPath = false;
         hasPath = hasPathCore(matrix,rows,cols,row-1,col,str,pathLength+1,isVisited)
                 || hasPathCore(matrix,rows,cols,row,col+1,str,pathLength+1,isVisited)
                 || hasPathCore(matrix,rows,cols,row+1,col,str,pathLength+1,isVisited)
                 || hasPathCore(matrix,rows,cols,row,col-1,str,pathLength+1,isVisited);

         if (!hasPath){
             isVisited[row*cols+col]=false;
         }
         return hasPath;
    }

    // =======测试代码========

    // A B T G
    // C F C S
    // J D E H

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

    // A B T G
    // C F C S
    // J D E H

    // BFCE
    public void test2() {
        char[] matrix = "ABTGCFCSJDEH".toCharArray();
        int rows = 3;
        int cols = 4;
        char[] str = "BFCE".toCharArray();
        if (hasPath(matrix, rows, cols, str))
            System.out.println("Test2 passed.");
        else
            System.out.println("Test2 failed.");
    }

    // matrix=null
    public void test3() {
        char[] matrix = null;
        int rows = 0;
        int cols = 0;
        char[] str = "BFCE".toCharArray();
        if (!hasPath(matrix, rows, cols, str))
            System.out.println("Test3 passed.");
        else
            System.out.println("Test3 failed.");
    }

    // str=null
    public void test4() {
        char[] matrix = "ABTGCFCSJDEH".toCharArray();
        int rows = 3;
        int cols = 4;
        char[] str = null;
        if (!hasPath(matrix, rows, cols, str))
            System.out.println("Test4 passed.");
        else
            System.out.println("Test4 failed.");
    }

    // A

    // A
    public void test5() {
        char[] matrix = "A".toCharArray();
        int rows = 1;
        int cols = 1;
        char[] str = "A".toCharArray();
        if (hasPath(matrix, rows, cols, str))
            System.out.println("Test5 passed.");
        else
            System.out.println("Test5 failed.");
    }

    // A

    // B
    public void test6() {
        char[] matrix = "A".toCharArray();
        int rows = 1;
        int cols = 1;
        char[] str = "B".toCharArray();
        if (!hasPath(matrix, rows, cols, str))
            System.out.println("Test6 passed.");
        else
            System.out.println("Test6 failed.");
    }

    // AAAA
    // AAAA
    // AAAA

    // AAAAAAAAAAAA
    public void test7() {
        char[] matrix = "AAAAAAAAAAAA".toCharArray();
        int rows = 3;
        int cols = 4;
        char[] str = "AAAAAAAAAAAA".toCharArray();
        if (hasPath(matrix, rows, cols, str))
            System.out.println("Test7 passed.");
        else
            System.out.println("Test7 failed.");
    }

    public static void main(String[] args) {
        StringPathInMatrix demo = new StringPathInMatrix();
        demo.test1();
        demo.test2();
        demo.test3();
        demo.test4();
        demo.test5();
        demo.test6();
        demo.test7();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值