Out of Boundary Paths (LeetCode 576): Solution and Explanation
A ball starts on one cell of an m x n grid and can roll up, down, left or right, including off the edge. Count how many move sequences of length at most maxMove end with the ball leaving the grid, modulo 10^9 + 7.
Intuition
Trying every path is hopeless: with four choices per move there are up to 4^50 sequences. But two paths that sit on the same cell after the same number of moves have exactly the same future. Whatever one can still do, the other can too.
So we only need to know how many paths are standing on each cell after k moves. Call that table dp. At the start it holds a single 1 on the start cell.
One move turns dp into the next table: every cell hands its count to each of its four neighbours. When a neighbour lies outside the grid, those paths have just escaped, and they are exactly the paths we want to count. Only border cells have outside neighbours, and a corner has two.
Run this maxMove times and add up every escape along the way. Each escaping path is counted once, at the move where it crosses the edge, so the running total is the answer.
Approach: Layered DP over the number of moves
- Create
dp, anm x ntable of zeros, and setdp[startRow][startColumn] = 1. Setcount = 0. - Repeat
maxMovetimes. Make a fresh zero tablenxt. - For every cell with
ways = dp[r][c] > 0, look at its four neighbours. If a neighbour is outside the grid, addwaystocount; otherwise addwaystonxtat that neighbour. Take everything modulo 10^9 + 7. - Replace
dpwithnxtand continue with the next move. - Return
count.
Step-by-step example
m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0
- Start: dp has 1 on (0, 0) and count = 0.
- Move 1: (0, 0) is a corner, so its upward and leftward neighbours are off the grid. 2 paths escape and count = 2.
- Its other two neighbours are inside, so after move 1 dp has 1 on (0, 1) and 1 on (1, 0).
- Move 2: (0, 1) is also a corner and spills 2 paths (up and right); (1, 0) spills 2 (left and down). count = 2 + 4 = 6.
- No moves are left, so the paths still inside never escape. The answer is 6.
Code: Python, Java, C++
1class Solution:
2 def findPaths(self, m: int, n: int, maxMove: int, startRow: int, startColumn: int) -> int:
3 MOD = 10**9 + 7
4 dp = [[0] * n for _ in range(m)]
5 dp[startRow][startColumn] = 1
6 count = 0
7 for _ in range(maxMove):
8 nxt = [[0] * n for _ in range(m)]
9 for r in range(m):
10 for c in range(n):
11 ways = dp[r][c]
12 if ways == 0:
13 continue
14 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
15 nr, nc = r + dr, c + dc
16 if nr < 0 or nr >= m or nc < 0 or nc >= n:
17 count = (count + ways) % MOD
18 else:
19 nxt[nr][nc] = (nxt[nr][nc] + ways) % MOD
20 dp = nxt
21 return count1class Solution {
2 public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
3 final int MOD = 1_000_000_007;
4 int[][] dp = new int[m][n];
5 dp[startRow][startColumn] = 1;
6 int count = 0;
7 int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
8 for (int move = 0; move < maxMove; move++) {
9 int[][] nxt = new int[m][n];
10 for (int r = 0; r < m; r++) {
11 for (int c = 0; c < n; c++) {
12 int ways = dp[r][c];
13 if (ways == 0) continue;
14 for (int[] d : dirs) {
15 int nr = r + d[0], nc = c + d[1];
16 if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
17 count = (count + ways) % MOD;
18 } else {
19 nxt[nr][nc] = (nxt[nr][nc] + ways) % MOD;
20 }
21 }
22 }
23 }
24 dp = nxt;
25 }
26 return count;
27 }
28}1class Solution {
2public:
3 int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
4 const int MOD = 1000000007;
5 vector<vector<int>> dp(m, vector<int>(n, 0));
6 dp[startRow][startColumn] = 1;
7 int count = 0;
8 int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
9 for (int move = 0; move < maxMove; move++) {
10 vector<vector<int>> nxt(m, vector<int>(n, 0));
11 for (int r = 0; r < m; r++) {
12 for (int c = 0; c < n; c++) {
13 int ways = dp[r][c];
14 if (ways == 0) continue;
15 for (auto& d : dirs) {
16 int nr = r + d[0], nc = c + d[1];
17 if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
18 count = (count + ways) % MOD;
19 } else {
20 nxt[nr][nc] = (nxt[nr][nc] + ways) % MOD;
21 }
22 }
23 }
24 }
25 dp = nxt;
26 }
27 return count;
28 }
29};Time and space complexity
O(maxMove * m * n)
Each of the maxMove rounds visits every cell once and does four constant-time updates.
O(m * n)
Only the current table and the next one are kept, each with m * n entries.
Other approaches
Memoised recursion on (moves left, row, col) (time O(maxMove * m * n), space O(maxMove * m * n))
Define f(k, r, c) as the number of escaping paths from (r, c) with k moves left: 1 if the cell is already off the grid, 0 if k is 0, otherwise the sum over four neighbours with k - 1. Caching the results gives the same complexity but uses O(maxMove * m * n) memory and deep recursion.
Plain path enumeration (time O(4^maxMove), space O(maxMove))
Recursively try every move sequence. It is easy to write and fine for tiny inputs, but the number of sequences grows like 4^maxMove.
Common mistakes
- Updating dp in place during a move. A count could then move twice in one round; always write into a fresh table.
- Forgetting that a corner cell (or every cell of a 1-wide grid) has more than one outside neighbour. Checking all four directions handles this automatically.
- Applying the modulo only at the end. Counts overflow 32-bit integers after a dozen or so moves, so reduce after every addition.
- Treating maxMove = 0 as an error. The ball simply never moves and the answer is 0.
Frequently asked questions
Why is it enough to store counts per cell instead of the paths?
The future of a path depends only on where it is and how many moves remain. All paths sharing a cell at the same move behave identically, so one number per cell captures them.
Does a path that leaves the grid ever come back?
No. Once the ball crosses the boundary the path ends and is counted. That is why escapes go into count rather than into the next table.
Can the 32-bit integer overflow in Java or C++?
Each stored value is below 10^9 + 7, so adding two of them stays below about 2.0 * 10^9, which still fits in a signed 32-bit int. Reducing after every single addition keeps it safe.
How is this related to Knight Probability or Unique Paths?
They use the same layered idea: a table of counts (or probabilities) per cell that is pushed forward one move at a time.