AlgoTales · Roadmap

Unique paths

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Unique paths counts the ways to travel from the top-left to the bottom-right of a grid moving only right or down. Every square equals the sum of the square above and the square to its left, with ones along the edges. It is the cleanest example of counting with a table.

Practical use cases

  • Web app: Game character route counts. A tile-based browser game wants to tell designers how many routes a character has across a level, to avoid levels that are too easy. Filling a table where each tile adds its upper and left neighbours gives the count at once. A 10-by-10 level has 48,620 routes, found with 100 additions. Level designers can compare several layouts side by side and quickly see which one gives players more or fewer possible routes.
  • Web app: Teaching demo for interns. An internal training tool shows interns how many ways a delivery robot can cross a floor map. The page animates the numbers appearing in each cell. The cell values appear one by one, so interns see that every number is just the sum of two neighbours, which makes the idea stick far better than a formula.
  • System: Robot planning and simulations. Robot path planners and probability simulations count or weigh routes through grids. Knowing the number of routes helps estimate chances. In each of these, the numbers grow quickly even on small boards, which is why counting with a table beats listing every route by walking through them.

The story: Mira's Cricket-Ball Maze

At Mira's school fair there was a game called the Cricket-Ball Maze: a rectangular board with pegs in rows and columns. A rolling ball starts at the top-left corner and may roll only right or down, one peg at a time, until it drops into the bucket at the bottom-right corner. "How many different paths can the ball take?" the stall owner asked, offering a chocolate to anyone with the right answer.

Kabir began drawing: right-right-down... but a 3 by 5 board already had far too many paths to list. Mira noticed something about the edges first: along the top edge, a ball can only come from the left, and along the left edge only from above. So every peg on the two edges has exactly one path to it.

For every other peg: the ball arrived either from above or from the left, so paths to this peg = paths to the peg above + paths to the peg on the left. She filled in the table row by row and the bucket at the corner held the answer: 15. She won the chocolate.

This is the unique paths problem. Compared with grid paths with blocked lanes, there are no obstacles, which makes the edges all 1s. And because each row only reads the row before, one single row of numbers is enough: just keep adding the box on the left into the current box.

How to spot this problem, and where you need it

You need only the count of different routes through a grid, not the routes themselves, and the count grows too quickly to list.

Signs you need it

  • The problem says "how many unique paths" from a start to an end, with moves like right and down.
  • A recursive solution takes forever on grids bigger than about 15 by 15.
  • The count is huge for a small grid, which tells you listing is hopeless.

Where to use it in a project

  • Level design checks in grid-based games and puzzles.
  • Teaching or demonstration pages that explain how many routes exist across a map.

The solution

Fill the first row and first column with 1, because there is just one straight way to reach those cells. For every other cell, add the value above and the value to the left. Work left to right, top to bottom. The bottom-right cell holds the final count. You can even keep only a single row, updating it as you go down.

Payoff: Before: counting routes by following every path, impossible past 15 by 15. After: a few hundred additions for a 20-by-20 grid.

Explain it like I am 8

Imagine Pascal's pyramid of stones, but on a flat board. Every square tells you how many ways you could have gotten there. The top and left edges are all ones because there is just one straight way. Each other square is the square above plus the square to its left.

How it works, step by step

  1. State: dp[r][c] = number of unique paths to reach cell (r, c).
  2. Base cases: the whole first row and the whole first column are 1.
  3. Transition: dp[r][c] = dp[r-1][c] + dp[r][c-1].
  4. Answer: the bottom-right box.
  5. Save memory: keep only one row. Start it as all 1s; for each new row, do row[c] += row[c-1] (the old row[c] is "above", the new row[c-1] is "left").

The code in four languages

PHP

<?php
// Unique paths in an m x n grid, moving only right or down.
// One row of numbers is enough (space optimisation).
function uniquePaths(int $m, int $n): int {
    $row = array_fill(0, $n, 1);                 // first row: every cell has exactly one path
    for ($r = 1; $r < $m; $r++) {
        for ($c = 1; $c < $n; $c++) {
            // row[c] (old value) is "from above", row[c-1] (new value) is "from the left".
            $row[$c] += $row[$c - 1];
        }
    }
    return $row[$n - 1];
}

echo uniquePaths(3, 5), "\n";                   // 15
echo uniquePaths(7, 3), "\n";                   // 28
echo uniquePaths(1, 1), "\n";                   // 1 (already at the bucket)

JavaScript

// Unique paths in an m x n grid, moving only right or down.
// One row of numbers is enough (space optimisation).
function uniquePaths(m, n) {
  const row = new Array(n).fill(1);              // first row: every cell has exactly one path
  for (let r = 1; r < m; r++) {
    for (let c = 1; c < n; c++) {
      // row[c] (old value) is "from above", row[c-1] (new value) is "from the left".
      row[c] += row[c - 1];
    }
  }
  return row[n - 1];
}

console.log(uniquePaths(3, 5));                  // 15
console.log(uniquePaths(7, 3));                  // 28
console.log(uniquePaths(1, 1));                  // 1 (already at the bucket)

Java

import java.util.*;

public class Main {
    // Unique paths in an m x n grid, moving only right or down.
    // One row of numbers is enough (space optimisation).
    static int uniquePaths(int m, int n) {
        int[] row = new int[n];
        Arrays.fill(row, 1);                         // first row: every cell has exactly one path
        for (int r = 1; r < m; r++) {
            for (int c = 1; c < n; c++) {
                // row[c] (old value) is "from above", row[c-1] (new value) is "from the left".
                row[c] += row[c - 1];
            }
        }
        return row[n - 1];
    }

    public static void main(String[] args) {
        System.out.println(uniquePaths(3, 5));       // 15
        System.out.println(uniquePaths(7, 3));       // 28
        System.out.println(uniquePaths(1, 1));       // 1 (already at the bucket)
    }
}

Go

package main

import "fmt"

// Unique paths in an m x n grid, moving only right or down.
// One row of numbers is enough (space optimisation).
func uniquePaths(m, n int) int {
	row := make([]int, n)
	for c := range row {
		row[c] = 1 // first row: every cell has exactly one path
	}
	for r := 1; r < m; r++ {
		for c := 1; c < n; c++ {
			// row[c] (old value) is "from above", row[c-1] (new value) is "from the left".
			row[c] += row[c-1]
		}
	}
	return row[n-1]
}

func main() {
	fmt.Println(uniquePaths(3, 5)) // 15
	fmt.Println(uniquePaths(7, 3)) // 28
	fmt.Println(uniquePaths(1, 1)) // 1 (already at the bucket)
}

Time: O(m × n) · Extra space: O(n). Every cell is added once; only one row is kept in memory at a time.

Watch out for

  • Starting the first row/column with 0 instead of 1, which makes every answer 0.
  • Mixing up rows and columns (m and n). The answer is symmetrical, but the loops must match the array length.
  • Using the one-row trick but looping the inner loop from 0 instead of 1, which breaks the first column.

Quick check

  1. How many paths reach any cell on the top row?
    • 0
    • 1
    • It depends on the column
  2. How many unique paths are there in a 2 × 2 grid?
    • 1
    • 3
    • 2
  3. In the one-row version, what does row[c] hold before the update row[c] += row[c-1]?
    • The answer for the left cell of this row
    • The count from the cell above (previous row)
    • Always 1