Looking for good programming challenges?

Use the search below to find our solutions for selected questions!

Out of Boundary Paths

Sharing is caring!

Problem Statement

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 10^9 + 7.
  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].

Example 1

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

Example 2

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

Solution

class Solution {
    final int MOD = 1000000007;
    
    public int findPaths(int m, int n, int N, int i, int j) {
        // dp[k][i][j] = number of paths with at most k steps starting from position (i,j)
        int[][][] dp = new int[N+1][m][n];
        
        for (int k=1; k<=N; k++){
            for (int r=0; r<m; r++) {
                for (int c=0; c<n; c++) {
                    if (r>0) {
                        dp[k][r][c] += dp[k-1][r-1][c];
                    } else {
                        dp[k][r][c] += 1;
                    }
                    dp[k][r][c] %= MOD;
                    
                    if (r==m-1) {
                        dp[k][r][c] += 1;
                    } else {
                        dp[k][r][c] += dp[k-1][r+1][c];
                    }
                    dp[k][r][c] %= MOD;
                    
                    if (c>0) {
                        dp[k][r][c] += dp[k-1][r][c-1];
                    } else {
                        dp[k][r][c] += 1;
                    }
                    dp[k][r][c] %= MOD;
                    
                    if (c==n-1) {
                        dp[k][r][c] += 1;
                    } else {
                        dp[k][r][c] += dp[k-1][r][c+1];
                    }
                    dp[k][r][c] %= MOD;
                }
            }
        }

        
        return dp[N][i][j];
    }
}