Grid paths
Intermediate · 10 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Grid paths counts or finds routes across a grid from one corner to another, moving only right or down, possibly around blocked squares. Each square's answer is built from the square above and the square to its left. It is the model for routes through any map-like table.
Practical use cases
- Web app: Warehouse robot route count. A warehouse dashboard shows a grid of aisles where some are blocked for maintenance. The manager wants the number of possible routes from the dock to a shelf, to check there is enough redundancy. Each cell sums the routes into it from above and from the left, giving the answer for the whole floor without listing any route. When an aisle is closed for repair, the manager marks it blocked and the counts redraw immediately, showing whether any safe route is left.
- Web app: Board-game move planner. A browser board game needs to tell the player how many ways remain to reach the goal square. Filling a grid of counts row by row shows the number in each square, and blocked squares simply count as zero. Designers can then drag a wall around on the board and see the route count change at once, which makes balancing the difficulty much quicker and more visual.
- System: Map routing and alignment grids. Map grids and text alignment tools fill tables where every cell depends on neighbours. The same pattern appears in robot navigation and in comparing DNA strings. In each of these, a table of counts is filled one square at a time, so the final corner holds the answer without any route being traced individually.
The story: The Delivery Boy and the Dug-up Lanes
Bunty delivers tiffins in Mira's town. The streets form a neat grid, like graph paper. He starts at the top-left corner and must reach the school at the bottom-right. To keep it simple he only walks right or down, never back. "How many different routes can I take?" he wondered, because he was bored of the same one.
Then the municipality dug up two lanes for pipes, and the roads there were blocked. Counting routes by drawing them all became a nightmare. Mira said, "Count for one crossing at a time. To stand on any crossing you must have come from the crossing above or the crossing on the left. So the number of routes to here is the routes to above plus the routes to the left."
And a blocked crossing? "Nobody can stand there," said Mira, "so its number is simply 0." That made the dug-up lanes disappear from every count automatically: a route trying to pass through them contributes nothing.
The table now has rows and columns, one box per crossing. This is 2D dynamic programming: the state has two parts (row and column), the transition looks up and left, and the base case is the start box. It is the standard grid paths problem.
How to spot this problem, and where you need it
You need the number of ways to get across a grid, possibly with blocked cells, and the number is too large to list one by one.
Signs you need it
- The input is a grid or a rectangle of size rows by columns, and moves are limited to right and down.
- Some squares are obstacles, and the question asks "how many different paths".
- A recursive path search takes forever once the grid reaches 15 by 15 or so.
Where to use it in a project
- Counting routes or redundancy in a warehouse, floor plan or network grid.
- Game and puzzle features that need the count of possible moves or paths.
The solution
Make a table the same size as the grid. Set the starting cell to 1 and blocked cells to 0. Fill row by row: a free cell's count equals the count of the cell above plus the count of the cell to its left, treating missing neighbours as 0. When you reach the target corner, its count is the total number of paths. Each cell is computed once.
Payoff: Before: tens of billions of paths to follow on a 20-by-20 grid. After: 400 additions.
Explain it like I am 8
Put your finger on the top-left corner of a chocolate bar. Each square tells you how many ways you could have wandered there. A square's number is simply the number on the square above it plus the number on the square to its left. A square with a "no entry" sign is worth 0.
How it works, step by step
- State:
dp[r][c]= number of routes from the start to the cell at rowr, columnc. - Base case:
dp[0][0] = 1, one way to be at the start (if the start itself is blocked, the answer is 0). - Transition: if the cell is blocked,
0. Otherwisedp[r][c] = dp[r-1][c] + dp[r][c-1](above plus left). - Edges: cells in the first row or first column have only one neighbour (the other side is outside the grid, count it as 0).
- Fill row by row, left to right, so above and left are ready. The answer is the bottom-right box.
The code in four languages
PHP
<?php
// Count routes from top-left to bottom-right moving only right or down.
// '#' marks a blocked cell.
function countRoutes(array $grid): int {
$rows = count($grid);
$cols = strlen($grid[0]);
$dp = array_fill(0, $rows, array_fill(0, $cols, 0));
for ($r = 0; $r < $rows; $r++) {
for ($c = 0; $c < $cols; $c++) {
if ($grid[$r][$c] === '#') { $dp[$r][$c] = 0; continue; } // blocked: no routes
if ($r === 0 && $c === 0) { $dp[$r][$c] = 1; continue; } // base case
$fromAbove = $r > 0 ? $dp[$r - 1][$c] : 0;
$fromLeft = $c > 0 ? $dp[$r][$c - 1] : 0;
$dp[$r][$c] = $fromAbove + $fromLeft;
}
}
return $dp[$rows - 1][$cols - 1];
}
echo countRoutes(["....", ".#..", "...#", "...."]), "\n"; // 4
echo countRoutes(["..", ".."]), "\n"; // 2JavaScript
// Count routes from top-left to bottom-right moving only right or down.
// '#' marks a blocked cell.
function countRoutes(grid) {
const rows = grid.length, cols = grid[0].length;
const dp = Array.from({ length: rows }, () => new Array(cols).fill(0));
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] === '#') { dp[r][c] = 0; continue; } // blocked: no routes
if (r === 0 && c === 0) { dp[r][c] = 1; continue; } // base case
const fromAbove = r > 0 ? dp[r - 1][c] : 0;
const fromLeft = c > 0 ? dp[r][c - 1] : 0;
dp[r][c] = fromAbove + fromLeft;
}
}
return dp[rows - 1][cols - 1];
}
console.log(countRoutes(["....", ".#..", "...#", "...."])); // 4
console.log(countRoutes(["..", ".."])); // 2Java
public class Main {
// Count routes from top-left to bottom-right moving only right or down.
// '#' marks a blocked cell.
static int countRoutes(String[] grid) {
int rows = grid.length;
int cols = grid[0].length();
int[][] dp = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (grid[r].charAt(c) == '#') { dp[r][c] = 0; continue; } // blocked: no routes
if (r == 0 && c == 0) { dp[r][c] = 1; continue; } // base case
int fromAbove = r > 0 ? dp[r - 1][c] : 0;
int fromLeft = c > 0 ? dp[r][c - 1] : 0;
dp[r][c] = fromAbove + fromLeft;
}
}
return dp[rows - 1][cols - 1];
}
public static void main(String[] args) {
System.out.println(countRoutes(new String[]{"....", ".#..", "...#", "...."})); // 4
System.out.println(countRoutes(new String[]{"..", ".."})); // 2
}
}Go
package main
import "fmt"
// Count routes from top-left to bottom-right moving only right or down.
// '#' marks a blocked cell.
func countRoutes(grid []string) int {
rows := len(grid)
cols := len(grid[0])
dp := make([][]int, rows)
for r := range dp {
dp[r] = make([]int, cols)
}
for r := 0; r < rows; r++ {
for c := 0; c < cols; c++ {
if grid[r][c] == '#' { // blocked: no routes
dp[r][c] = 0
continue
}
if r == 0 && c == 0 { // base case
dp[r][c] = 1
continue
}
fromAbove, fromLeft := 0, 0
if r > 0 {
fromAbove = dp[r-1][c]
}
if c > 0 {
fromLeft = dp[r][c-1]
}
dp[r][c] = fromAbove + fromLeft
}
}
return dp[rows-1][cols-1]
}
func main() {
fmt.Println(countRoutes([]string{"....", ".#..", "...#", "...."})) // 4
fmt.Println(countRoutes([]string{"..", ".."})) // 2
}Time: O(rows × cols) · Extra space: O(rows × cols). One box per cell, two additions per box. Keeping just the previous row would cut space to one row.
Watch out for
- Not setting blocked cells to 0 (leaving stale values), so routes seem to pass through walls.
- Reading
dp[r-1][c]in the first row ordp[r][c-1]in the first column, which is off the grid. - Forgetting that a blocked start or a blocked finish makes the answer 0.
Quick check
- How many routes reach a cell, if the cell above has 3 and the cell to the left has 2?
- 6
- 5
- 1
- What number goes in a blocked cell?
- 1
- The sum of its neighbours
- 0
- Why fill the table row by row, left to right?
- So the cells above and to the left are already known
- Because rows are faster
- To use less memory