#576
Out of Boundary Paths
MediumDynamic ProgrammingDynamic ProgrammingRecursion
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(4^maxMove) | O(m * n * maxMove) |
| Space | O(maxMove) | O(m * n * maxMove) |
💡
Intuition
Time O(m * n * maxMove)Space O(m * n * maxMove)
The optimal solution uses dynamic programming to store the number of ways to reach each cell in the grid for each number of moves left. This avoids recalculating paths for the same state multiple times, significantly improving efficiency.
⚙️
Algorithm
4 steps- 1Step 1: Create a 3D DP array where dp[i][j][k] represents the number of ways to reach cell (i, j) with k moves left.
- 2Step 2: Initialize the base case where if the ball is out of bounds, it contributes 1 to the count.
- 3Step 3: Iterate through all possible moves from 0 to maxMove and update the DP table based on previous states.
- 4Step 4: Sum all the ways from the DP table for the starting position after maxMove moves.
solution.py12 lines
1def findPaths(m, n, maxMove, startRow, startColumn):
2 dp = [[[0] * (maxMove + 1) for _ in range(n)] for _ in range(m)]
3 mod = 10**9 + 7
4 for moves in range(1, maxMove + 1):
5 for r in range(m):
6 for c in range(n):
7 if r == 0: dp[r][c][moves] += 1
8 if r == m - 1: dp[r][c][moves] += 1
9 if c == 0: dp[r][c][moves] += 1
10 if c == n - 1: dp[r][c][moves] += 1
11 dp[r][c][moves] += (dp[r-1][c][moves-1] + dp[r+1][c][moves-1] + dp[r][c-1][moves-1] + dp[r][c+1][moves-1]) % mod
12 return dp[startRow][startColumn][maxMove] % modℹ
Complexity note: The time complexity is O(m * n * maxMove) because we fill a 3D array where each dimension corresponds to the grid dimensions and the number of moves. The space complexity is also O(m * n * maxMove) due to the 3D DP array.
- 1The number of paths grows exponentially with the number of moves.
- 2Dynamic programming significantly reduces redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.