We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Out of Boundary Paths

Number: 576

Difficulty: Medium

Paid? No

Companies: Bloomberg, Adobe, Amazon, Baidu


Problem Description

We are given an m x n grid with a ball placed at position [startRow, startColumn]. The ball can move in four directions (up, down, left, right). We are allowed a maximum of maxMove moves. The goal is to find the number of paths that result in the ball moving out of the grid boundary. Since the answer can be huge, return the result modulo 10^9 + 7.


Key Insights

  • Use Dynamic Programming (DP) as the state is defined by (current row, current column, moves remaining).
  • Transitions are made from a cell to its four adjacent cells.
  • If the ball moves out of bounds, it contributes to one valid path.
  • States can be memoized to avoid recomputation and optimize the recursive solution.

Space and Time Complexity

Time Complexity: O(maxMove * m * n), since we compute each state at most once. Space Complexity: O(maxMove * m * n) for the memoization table.


Solution

We use a recursive dynamic programming (or memoization) approach. Define a function dp(i, j, movesLeft) that returns the number of ways to move out of bounds starting from cell (i, j) with movesLeft moves remaining. For each move from the current cell, check:

  1. If the cell is out of bounds, return 1 (base case).
  2. If no moves are left (movesLeft == 0) and we are still inside, return 0.
  3. Otherwise, use recursion to explore all four directions and sum the paths. Store results in a memoization table to avoid recomputation, then return the computed value modulo 10^9 + 7.

Code Solutions

MOD = 10**9 + 7

def findPaths(m, n, maxMove, startRow, startColumn):
    # Initialize memo dictionary to cache the states
    memo = {}
    
    def dp(i, j, movesLeft):
        # If out of grid bounds, it's a valid path
        if i < 0 or i >= m or j < 0 or j >= n:
            return 1
        # No moves left and still inside the grid means no valid path out
        if movesLeft == 0:
            return 0
        # Check if we already computed this state
        if (i, j, movesLeft) in memo:
            return memo[(i, j, movesLeft)]
        
        count = 0
        # Four possible directions: up, down, left, right
        count = (dp(i - 1, j, movesLeft - 1) +
                 dp(i + 1, j, movesLeft - 1) +
                 dp(i, j - 1, movesLeft - 1) +
                 dp(i, j + 1, movesLeft - 1)) % MOD
        
        memo[(i, j, movesLeft)] = count
        return count

    return dp(startRow, startColumn, maxMove)

# Example usage
if __name__ == "__main__":
    print(findPaths(2, 2, 2, 0, 0))  # Expected output: 6
← Back to All Questions