Problem 576

Abstract / Summary

A robot moves on a grid from start to finish in a set number of steps and may go outside boundaries; count the ways this can happen.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
24 lines | 921 bytes | submitted January 29, 2024 | GitHub   4% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (400k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 6 | μ = 5.42 | σ = 1.78

Complexity Analysis

Time: polynomial
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
38 links | 24 authors | 8 languages

Videos

11 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

5 solutions   January 29, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • 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