剑指Offer 牛客 JZ65 矩阵中的路径 较难 递归

题目:
在这里插入图片描述
题目链接

思路:
矩阵中找一条路径,使用嵌套循环假设每个位置都是一个起点
求解是否存在路径:
使用递归,根据题目描述,每一步可以走4个方向,所以4个方向都走,判断是否有解
有解的条件:1.当前值和要寻找的值相等且当前值未被访问过, 2.当前值是最后一个要寻找的值
有了以上思路,很快可以写出递归,注意递归结束条件以及可以适当“剪枝”
递归结束条件需要判断当前位置是否越界
剪枝的内容包括只要有任意一个方向有解,即可返回true,不需要继续求解因为题目不要求求所有路径

综上,使用一个bool二维数组表示当前位置是否被遍历过,注意!!结束递归本层的是否要把遍历过的标志信息恢复为false

代码:

public class Solution {
    boolean[][] marked;
    /**
     * 
     * @param matrix 数据数组,题目给成一个一维的
     * @param rows  行数
     * @param cols  列数
     * @param str  要寻找的字符串,题目给成一个一维数组
     * @return
     */
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str)
    {
        if (matrix == null || matrix.length == 0){
            return false;
        }
        //当前要寻找哪个字符
        int index = 0;
        marked = new boolean[rows][cols];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (process(matrix, rows, cols, str, i, j, index)){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean process(char[] matrix, int rows, int cols, char[] str, int i, int j, int index){
    	//判断是否越界
        if (i < 0 || i >= rows || j < 0 || j >= cols || index >= str.length){
            return false;
        }
        //二维行,列在一维数组上的对应下标关系
        if (!marked[i][j] && matrix[i*cols+j] == str[index]){
            if (index == str.length-1){
                return true;
            }
            marked[i][j] = true;
            index++;
            boolean next1;
            boolean next2;
            boolean next3;
            boolean next4;
            //向左
            next1 = process(matrix, rows, cols, str, i, j-1, index);
            if (next1){
                return true;
            }
            //向上
            next2 = process(matrix, rows, cols, str, i-1, j, index);
            if (next2){
                return true;
            }
            //向右
            next3 = process(matrix, rows, cols, str, i, j+1, index);
            if (next3){
                return true;
            }
            //向下
            next4 = process(matrix, rows, cols, str, i+1, j, index);
            if (next4){
                return true;
            }
            //恢复标志位
            marked[i][j] = false;
            return false;
        }else {
            return false;
        }
    }
}

参数示例:
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值