576. Out of Boundary Paths

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:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/out-of-boundary-paths
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

dp[x][y][k] 表示从坐标x,y出发,走k步到边缘的路径数目。那么dp[x][y][k]就表示他的上下左右走k - 1步的和。
class Solution {
    public int findPaths(int m, int n, int N, int i, int j) {
        int [][][]dp = new int[m][n][N + 1];
        for (int k = 1; k <= N; k++) {
            for (int x = 0; x < m; x++) {
                for (int y = 0; y < n; y++) {
                    long up = (x == 0) ? 1: dp[x - 1][y][k - 1];
                    long down = (x == m - 1) ? 1: dp[x + 1][y][k - 1];
                    long left = (y == 0) ? 1 : dp[x][y - 1][k - 1];
                    long right = (y == n - 1) ? 1 : dp[x][y + 1][k - 1];
                    dp[x][y][k] = (int)((up + down + left + right) % 1000000007);
                }
            }
        }
        return dp[i][j][N];
    }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值