Python 0576.py
class Solution:
def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
result = 0
todo = defaultdict(int)
todo[( startColumn, startRow )] = 1
for _ in range(maxMove):
next = defaultdict(int)
for x, y in todo:
current = todo[( x, y )]
if 0 <= x < n and 0 <= y < m:
next[( x + 1, y)] += current
next[( x - 1, y)] += current
next[( x, y + 1)] += current
next[( x, y - 1)] += current
else:
# copy paths already out of bounds
next[( x, y )] += current
todo = next
for x, y in todo:
if x == -1 or x == n or y == -1 or y == m:
result += todo[( x, y )]
return result % 1_000_000_007
Difficulty
and has an acceptance rate of about 48% (400k+ submissions).
Typical patterns to solve this problem:
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation computes the number of distinct ways a ball can move out of a rectangular grid after a limited number of moves. The grid dimensions are m rows by n columns, the ball starts at (startRow, startColumn), and it may move up, down, left, or right up to maxMove steps. The result is returned modulo 1 000 000 007. The algorithm employs a dynamic-programming style breadth-first expansion, tracking only the positions that are reachable at each step.
Initialization
The algorithm begins by creating a counter for the final answer and a dictionary that records how many ways the ball can be at each coordinate after the current number of moves.
result = 0
todo = defaultdict(int)
todo[( startColumn, startRow )] = 1
The key (startColumn, startRow) stores the single initial path. Using defaultdict(int) eliminates the need for explicit existence checks when incrementing counts.
Iterative Expansion
A loop runs exactly maxMove times, each iteration representing one additional move. Inside the loop a fresh dictionary next is prepared to accumulate the counts for the next step.
for _ in range(maxMove):
next = defaultdict(int)
for x, y in todo:
current = todo[( x, y )]
if 0 <= x < n and 0 <= y < m:
next[( x + 1, y)] += current
next[( x - 1, y)] += current
next[( x, y + 1)] += current
next[( x, y - 1)] += current
else:
# copy paths already out of bounds
next[( x, y )] += current
todo = next
In-bounds Expansion
When a coordinate lies inside the grid (0 ≤ x < n and 0 ≤ y < m), the algorithm generates four new entries, one for each possible direction. The count current is added to each neighbor, effectively propagating all existing paths forward.
Out-of-bounds Propagation
If a coordinate is already outside the grid, the algorithm does not generate further moves; instead, it copies the existing count to the same out-of-bounds key in next. This ensures that once a path has left the grid, it remains counted in subsequent iterations without being altered by additional moves.
Accumulating the Answer
After completing all move iterations, the dictionary todo contains counts for every position reachable after exactly maxMove steps, including those that are out of bounds. The final loop scans this dictionary and adds the counts for all out-of-bounds keys to result.
for x, y in todo:
if x == -1 or x == n or y == -1 or y == m:
result += todo[( x, y )]
return result % 1_000_000_007
The condition x == -1 or x == n or y == -1 or y == m captures the four possible exit lines of the rectangle. The modulo operation is applied only once at the end, which reduces the number of expensive modulo calculations during the main loop.
Edge Cases Handled
The code gracefully handles the situation where a path steps outside the grid before all moves are exhausted. By copying out-of-bounds counts unchanged into the next iteration, it guarantees that such paths continue to contribute to the final total regardless of remaining moves.
If the starting cell itself were out of bounds (an unlikely input but theoretically possible), the initial todo entry would be treated as out of bounds from the first iteration onward, and the final accumulation would include it directly.
When maxMove is zero, the outer loop does not execute, leaving todo with only the initial position. The final scan then adds to result only if the start is already out of bounds, correctly yielding zero for an in-bounds start.
Performance Optimizations
The implementation avoids storing the entire m × n grid for each step. Instead, it keeps a sparse mapping of only those coordinates that have a non-zero number of paths, dramatically reducing memory usage when many cells remain unreachable.
Using defaultdict(int) eliminates conditional checks for key existence, allowing direct increment operations.
The algorithm performs a single modulo operation after all iterations, which is cheaper than applying the modulus after each addition.
By reassigning todo = next at the end of each iteration, the code discards the previous step’s data, ensuring that only the current frontier occupies memory.
The explicit check for out-of-bounds coordinates prevents unnecessary generation of neighbor positions that would immediately be discarded, focusing computation on viable moves.
Concluding Remarks
Overall, the solution follows a clear dynamic-programming pattern: it iteratively builds the distribution of path counts across the grid, respects boundary conditions by preserving out-of-bounds counts, and aggregates the final answer efficiently. The use of dictionaries for sparse state representation and the deferment of the modulo operation are the primary contributors to its performance characteristics.
ELI5 - Simplified Explanation
Imagine a tiny ball sitting on a grid that looks like a sheet of graph paper. The goal is to see how many different ways that ball can tumble off the edge of the paper within a certain number of rolls.
Everything starts with the ball at a specific spot on the grid. A dictionary keeps track of how many ways the ball can be at any given coordinate. At the very beginning, there is exactly one way for the ball to be at the starting spot.
Because the ball is allowed to move a set number of times, the code repeats a process for each of those moves. During each step, it looks at where the ball could be and considers all four directions it might roll next: up, down, left, or right. If the ball is still somewhere on the paper, it plans the next set of possible positions. If it has already rolled off the edge, it stays there.
After all the moves are finished, the computer checks the spots that are outside the boundaries of the paper. It counts up all the times the ball landed off the edge during its journey. This total count tells how many unique paths lead the ball to fall off the grid. Finally, the number is made smaller by a large limit to keep it manageable.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | C++ | Java | Python | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||||
| LeetcodeHelp | C++ | Java | Python | ||||||
| MemoryLimitExceeded | C++ | Python | |||||||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fpdjsns | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JS | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||
| MemoryLimitExceeded | Python, C++ | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fpdjsns | C++ | ||||||||
| gouthampradhan | Java | ||||||||
| halfrost | Go | ||||||||
| JoshCrozier | JavaScript | ||||||||
| keineahnung2345 | C++ | ||||||||
| linouk23 | C++ | ||||||||
| lkwq007 | Python | ||||||||
| ruoru | Rust | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| wisdompeak | C++ | ||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 688: Knight Probability in Chessboard
Solved On The Same Day
- problem 2068: Check Whether Two Strings are Almost Equivalent
- problem 1963: Minimum Number of Swaps to Make the String Balanced
- problem 1968: Array With Elements Not Equal to Average of Neighbors
- problem 1996: The Number of Weak Characters in the Game
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality