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

Approach 1: DP. For each step, update the number of ways that the ball lands on each cell.

# Code (Python)

Approach 1:

MOD_VAL = 1e9 + 7

class Solution:
    def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
        total = 0
        locations = {(i, j): 1}
        for i in range(N):
            new_locations = {}
            for location, ways in locations.items():
                for delta in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                    new_location = (location[0] + delta[0], location[1] + delta[1])
                    if self._out_of_bound(new_location, m, n):
                        total = (total + ways) % MOD_VAL
                    else:
                        if new_location not in new_locations:
                            new_locations[new_location] = 0
                        new_locations[new_location] += ways % MOD_VAL
            locations = new_locations
        return int(total)
    
    def _out_of_bound(self, location, m, n):
        return not(0 <= location[0] < m and 0 <= location[1] < n)

# Code (C++)

Approach 1:

Approach 2: