Question:

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

Example 2:

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

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].

Solution:

  • Method 1: DP
      class Solution {        
          public int findPaths(int m, int n, int N, int i, int 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++){
                          // (r, c) means the current position of a node.
                          int tempRow = 0, tempCol = 0;
                          for(int d = 0; d < 4; d++){
                              // (tempRow, tempCol) means the next posible position
                              tempRow = r + dir[d][0];
                              tempCol = c + dir[d][1];
                              if(tempRow < 0 || tempRow >= m || tempCol < 0 || tempCol >= n){
                                  // if next position is out of boundary, current index add 1.
                                  dp[k][r][c] += 1;
                              }else{
                                  // if next position is within the boundary, we add that ways to current one.
                                  dp[k][r][c] = (dp[k][r][c] + dp[k - 1][tempRow][tempCol]) % 1000000007;
                              }
                          }
                      }
                  }
              }
              return dp[N][i][j];
          }
      }
    

Reference

  1. 花花酱 LeetCode 576. Out of Boundary Paths