【LeetCode】576. 出界的路径数

题目

LeetCode自搜

题解

建议看《忆甜思苦,DFS + 记忆化搜索》,链接:
https://leetcode-cn.com/problems/out-of-boundary-paths/solution/yi-tian-si-ku-dfs-ji-yi-hua-sou-suo-by-i-iteo/
我是看了官方题解自闭后,发现的这个宝藏题解
如果直接看觉得过于简洁的话,可以先看一遍更详细的官方题解。

代码

class Solution {
    private static final int[][] DIR = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 
    private static final int MOD = (int)(1e9+7);
    
    private Map<Integer, Integer> map = new HashMap<>();
    
    public int findPaths(int m, int n, int moves, int r, int c) {
        //情况一:出界,+1
        if (r < 0 || r >= m || c < 0 || c >= n) {
            return 1;
        }
        
        //情况二:moves步数用完
        if (moves == 0) return 0;
        
        //情况三:已求,直接取
        int key = r*2500+c*50+moves;
        if (map.containsKey(key)) {
            return map.get(key);
        }
        
        //Start
        int rst = 0;
        for(int[] d : DIR) {
            rst = (rst + findPaths(m, n, moves-1, r+d[0], c+d[1]))%MOD;
        }
        map.put(key, rst);
        return rst;
    }
}

心得

1.

private static final

static:经常调用时使用
final:常量不变时使用

 
2.

private Map<Integer, Integer> map = new HashMap<>();

        if (map.containsKey(key)) {
            return map.get(key);
        }
        
        map.put(key, rst);

Map映射的 定义、取值、添加

 
3.

int key = r*2500+c*50+moves;

二位数组一维化(题目里为mod50的三维矩阵,这里以mod4的二维矩阵举例如图)
在这里插入图片描述

 
4.

private static final int[][] DIR = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; 

移动方向表示

 
5.

5.for(int[] d : DIR) 

特别的for循环

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值