Grid paths
30 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Grid dynamic programming solves pathfinding and optimization problems on 2D matrices. Before jumping to a table, we start with simple recursion and see why it repeats work.
Brute Force Recursion and Why It Is Slow
Grid DP fills a table with one cell per grid position, where each cell stores the answer for reaching that position, such as the number of paths or the cheapest cost, built from its top and left neighbours.
Plain grid recursion counts paths from the top-left cell (0, 0) to the bottom-right cell (m - 1, n - 1) by trying both moves from every cell (r, c): move down to (r + 1, c) or move right to (r, c + 1).
int countPaths(int r, int c, int m, int n) { if (r >= m || c >= n) return 0; // walked outside the grid if (r == m - 1 && c == n - 1) return 1; // reached the destination return countPaths(r + 1, c, m, n) // move down + countPaths(r, c + 1, m, n); // move right}When you reach the destination, you return 1. If you walk outside the grid boundary, you return 0. The total paths from (r, c) is countPaths(r + 1, c) + countPaths(r, c + 1).
Why is this slow? At each step, the recursion splits into two branches. For an m by n grid, this tree has depth m + n and branches up to 2^(m + n) times. The function visits cell (1, 1) through (0, 0)->(1, 0)->(1, 1) and also through (0, 0)->(0, 1)->(1, 1), repeating the exact same sub-grid calculation billions of times on even a 15 by 15 board.
Example 1 · Unique Paths, Plain Recursion: O(2^(m+n)) Time
public class GridRecursion { static int calls = 0;
public static int paths(int r, int c, int m, int n) { calls++; if (r >= m || c >= n) return 0; if (r == m - 1 && c == n - 1) return 1; return paths(r + 1, c, m, n) + paths(r, c + 1, m, n); }
public static void main(String[] args) { System.out.println("Paths in 3x3: " + paths(0, 0, 3, 3)); System.out.println("Calls for 3x3: " + calls); calls = 0; System.out.println("Paths in 8x8: " + paths(0, 0, 8, 8)); System.out.println("Calls for 8x8: " + calls); }}Paths in 3x3: 6 Calls for 3x3: 27 Paths in 8x8: 3432 Calls for 8x8: 18875
What this code does
- Every cell makes two calls, so the number of calls explodes: 27 calls for a 3 by 3 grid but 18,875 for 8 by 8.
- The cell (1, 1) is reached by many different routes, and its sub-grid is solved again each time.
- The answer is right but the work grows exponentially.
Example 2 · Unique Paths, Memoization: O(m x n) Time, O(m x n) Space
public class GridMemo { static int calls = 0;
public static int paths(int r, int c, int m, int n, int[][] memo) { calls++; if (r >= m || c >= n) return 0; if (r == m - 1 && c == n - 1) return 1; if (memo[r][c] != 0) return memo[r][c]; memo[r][c] = paths(r + 1, c, m, n, memo) + paths(r, c + 1, m, n, memo); return memo[r][c]; }
public static void main(String[] args) { System.out.println("Paths in 3x3: " + paths(0, 0, 3, 3, new int[3][3])); System.out.println("Calls for 3x3: " + calls); calls = 0; System.out.println("Paths in 8x8: " + paths(0, 0, 8, 8, new int[8][8])); System.out.println("Calls for 8x8: " + calls); }}Paths in 3x3: 6 Calls for 3x3: 17 Paths in 8x8: 3432 Calls for 8x8: 127
What this code does
- memo[r][c] holds the paths from cell (r, c) to the destination; 0 means not computed yet.
- There are only m x n cells, each solved once: 127 calls for 8 by 8 instead of 18,875.
- The cost is an m by n memo table plus recursion depth m + n.
From Overlapping Paths to a 2D Table
Notice that to land on cell (i, j), you can only arrive from two places: the cell directly above (i - 1, j) or the cell directly to the left (i, j - 1).
Unique paths in a 3 by 3 grid
Step 1 of 5
| Row | 0 | 1 | 2 |
|---|---|---|---|
| 0 | 1 | 1 | 1 |
| 1 | 1 | ||
| 2 | 1 |
Example 3 · Unique Paths, 2D Table: O(m x n) Time, O(m x n) Space
public class GridTable { public static int paths(int m, int n) { int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i == 0 || j == 0) { dp[i][j] = 1; } else { dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; } } } return dp[m - 1][n - 1]; }
public static void main(String[] args) { System.out.println("Paths in 3x3: " + paths(3, 3)); System.out.println("Paths in 3x7: " + paths(3, 7)); System.out.println("Paths in 8x8: " + paths(8, 8)); }}Paths in 3x3: 6 Paths in 3x7: 28 Paths in 8x8: 3432
What this code does
- The first row and column have one route each, so they start at 1.
- Every other cell is the cell above plus the cell to its left, so the loops need no recursion and no call stack.
- The table keeps all m x n cells, which the next example reduces to one row.
Example 4 · Unique Paths, One Row: O(m x n) Time, O(n) Space
public class UniquePathsDemo { public static int uniquePaths(int m, int n) { int[] dp = new int[n]; for (int j = 0; j < n; j++) dp[j] = 1; for (int i = 1; i < m; i++) { for (int j = 1; j < n; j++) { dp[j] += dp[j - 1]; } } return dp[n - 1]; }
public static void main(String[] args) { System.out.println("Paths in 3x7: " + uniquePaths(3, 7)); System.out.println("Paths in 3x3: " + uniquePaths(3, 3)); }}Paths in 3x7: 28 Paths in 3x3: 6
What this code does
- Allocates a 1D array of size n to track paths for the current row.
- Cell dp[j] accumulates the value above plus the newly computed left neighbor.
- Runs in O(m * n) time and O(n) auxiliary space.
Instead of recalculating, we build a 2D table dp[i][j] where each entry stores the number of ways to reach (i, j). The recurrence relation is dp[i][j] = dp[i - 1][j] + dp[i][j - 1]. Cells along the first row and first column have only one arrival direction, so they start initialized to 1. Filling the table row by row takes O(m * n) time and O(m * n) space.
Predict the output
Predict the table value
Read the program and choose what it prints.
Round 1 of 2
Each cell is the cell above plus the cell to its left. What is printed?
Obstacles and Boundary Conditions
An obstacle is a blocked cell (grid[i][j] == 1) that no path can pass through, so it contributes 0 paths. In recursion, a blocked cell (i, j) immediately returns 0.
int uniquePathsWithObstacles(int[][] grid) { int m = grid.length, n = grid[0].length; int[][] dp = new int[m][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 1) dp[i][j] = 0; // blocked: no paths else if (i == 0 && j == 0) dp[i][j] = 1; // open start cell else dp[i][j] = (i > 0 ? dp[i - 1][j] : 0) + (j > 0 ? dp[i][j - 1] : 0); } } return dp[m - 1][n - 1];}In our table, we do the exact same thing: whenever grid[i][j] == 1, we set dp[i][j] = 0. That stops paths from continuing through that cell.
If the start cell (0, 0) or the exit cell (m - 1, n - 1) is blocked, the answer is 0. Also, if an obstacle appears on the first row or first column, all cells after it on that same line stay 0 because no path can jump over an obstacle.
Minimum Path Sum and In-Place Memory
Instead of counting paths, minimum path sum asks for the cheapest route from top-left to bottom-right. Plain recursion checks every path in O(2^(m + n)) time, which freezes for large grids.
Example 5 · Minimum Path Sum Across Weighted Grid
public class MinPathSumDemo { public static int minPathSum(int[][] grid) { int m = grid.length; int n = grid[0].length; int[] dp = new int[n]; dp[0] = grid[0][0]; for (int j = 1; j < n; j++) { dp[j] = dp[j - 1] + grid[0][j]; } for (int i = 1; i < m; i++) { dp[0] += grid[i][0]; for (int j = 1; j < n; j++) { dp[j] = Math.min(dp[j], dp[j - 1]) + grid[i][j]; } } return dp[n - 1]; }
public static void main(String[] args) { int[][] grid = { {1, 3, 1}, {1, 5, 1}, {4, 2, 1} }; System.out.println("Min path sum: " + minPathSum(grid)); }}Min path sum: 7
What this code does
- Initializes the first row with cumulative sums from left to right.
- Updates each cell with its value plus the minimum of above and left.
- Path 1 -> 3 -> 1 -> 1 -> 1 yields optimal total cost 7.
Example 6 · Triangle Minimum Total Path
public class TriangleMinPathDemo { public static int minimumTotal(int[][] triangle) { int n = triangle.length; int[] dp = triangle[n - 1].clone(); for (int r = n - 2; r >= 0; r--) { for (int c = 0; c <= r; c++) { dp[c] = triangle[r][c] + Math.min(dp[c], dp[c + 1]); } } return dp[0]; }
public static void main(String[] args) { int[][] triangle = { {2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3} }; System.out.println("Triangle min total: " + minimumTotal(triangle)); }}Triangle min total: 11
What this code does
- Initializes dp array with the bottom base row of the triangle.
- Collapses rows upward by choosing the cheaper of adjacent downward children.
- Apex value dp[0] contains minimal path cost 2 + 3 + 5 + 1 = 11.
With dynamic programming, each cell chooses the cheaper neighbor and adds its own cost: dp[i][j] = grid[i][j] + Math.min(dp[i - 1][j], dp[i][j - 1]). Because cell (i, j) only needs the cell above and the cell to its left, we can write the new sums directly into the input grid itself, reducing extra memory to O(1).
Next step
Check your understanding
10 quick questions