576. Out of Boundary Paths

本文介绍了一种使用动态规划解决迷宫中球的路径问题的方法。在一个m x n的网格中,从给定的起点开始,球可以向四个方向移动,目标是计算在最多N次移动后,球出界的不同路径数量。文章详细解释了动态规划的实现过程,并提供了C++代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There is an m by n grid with a ball. Given the start coordinate (i,j) of the ball, you can move the ball to adjacent cell or cross the grid boundary in four directions (up, down, left, right). However, you can at most move N times. Find out the number of paths to move the ball out of grid boundary. The answer may be very large, return it after mod 109 + 7.

 

Example 1:

Input: m = 2, n = 2, N = 2, i = 0, j = 0
Output: 6
Explanation:

Example 2:

Input: m = 1, n = 3, N = 3, i = 0, j = 1
Output: 12
Explanation:

 

Note:

  1. Once you move the ball out of boundary, you cannot move it back.
  2. The length and height of the grid is in range [1,50].
  3. N is in range [0,50].
 

Approach #1: DP. [C++]

class Solution {
public:
    int findPaths(int m, int n, int N, int i, int j) {
        const int mod = 1000000007;
        vector<vector<vector<int>>> dp(N+1, vector<vector<int>>(m, vector<int>(n, 0)));
        vector<int> dirs = {1, 0, -1, 0, 1};
        for (int s = 1; s <= N; ++s) {
            for (int x = 0; x < m; ++x) {
                for (int y = 0; y < n; ++y) {
                    for (int k = 0; k < 4; ++k) {
                        int dx = x + dirs[k];
                        int dy = y + dirs[k+1];
                        if (dx < 0 || dy < 0 || dx >= m || dy >= n) 
                            dp[s][x][y] += 1;
                        else 
                            dp[s][x][y] = (dp[s][x][y] + dp[s-1][dx][dy]) % mod;
                    }
                }
            }
        }
        return dp[N][i][j];
    }
};

  

Analysis:

Observation:

Number of paths start from (i, j) to out of boundary <=> Number of paths start from out of boundary to (i, j).

 

dp[N][i][j] : Number of paths start from out of boundary to (i, j) by moving N steps.

dp[*][y][x] = 1, if (x, y) are out of boundary

dp[s][i][j] = dp[s-1][i+1][j] + dp[s-1][i-1][j] + dp[s-1][i][j+1] + dp[s-1][i][j-1]

 

Ans: dp[N][i][j]

 

Time complexity: O(N*m*n)

Space complexity: O(N*m*n) -> O(m*n)

 

Reference:

http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-576-out-of-boundary-paths/

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/10498491.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值