文章目录
- 576. 出界的路径数
 
本刷题专栏记录自己的记忆化搜索的做题。
576. 出界的路径数
题目链接及描述:
 https://leetcode.cn/problems/out-of-boundary-paths/description/

 
 第一次看到这个题目可能先入为主了,首先想到的是使用动态规划做,但动态规划一般都是单方向的,而这道题目可以重复进入(这点就是记忆化所在)可以参考三叶的https://leetcode.cn/problems/out-of-boundary-paths/solutions/936439/gong-shui-san-xie-yi-ti-shuang-jie-ji-yi-asrz/,这道题目使用动态规划还是有点难的,采用题解中提供的记忆化搜索的方法。后面再把可重复动态规划学习一下。
class Solution {
    int MOD = (int)1e9+7;
    int m, n, max;
    int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
    int[][][] cache;
    public int findPaths(int _m, int _n, int _max, int r, int c) {
        m = _m; n = _n; max = _max;
        cache = new int[m][n][max + 1];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                for (int k = 0; k <= max; k++) {
                    cache[i][j][k] = -1;
                }
            }
        }
        return dfs(r, c, max);
    }
    int dfs(int x, int y, int k) {
        if (x < 0 || x >= m || y < 0 || y >= n) return 1;
        if (k == 0) return 0;
        if (cache[x][y][k] != -1) return cache[x][y][k];
        int ans = 0;
        for (int[] d : dirs) {
            int nx = x + d[0], ny = y + d[1];
            ans += dfs(nx, ny, k - 1);
            ans %= MOD;
        }
        cache[x][y][k] = ans;
        return ans;
    }
}
                

![【题解】【模拟】—— [NOIP2013 普及组] 表达式求值](https://i-blog.csdnimg.cn/direct/f782c1acde024adb925001c00e7952f4.jpeg#pic_center)
















