Print all possible paths from top left to bottom right of a mXn matrix
Pattern: Rat in a maze
Moving only right or down, every path from the top-left to the bottom-right is a sequence of choices. Recurse with both choices, collecting the values along the way, and record the path at the corner.
The problem
Given an m × n matrix, return every path from the top-left cell to the bottom-right cell that moves only right or
down, each written as the list of values it passes through. For example, [[1, 2, 3], [4, 5, 6]] gives
[1, 4, 5, 6], [1, 2, 5, 6] and [1, 2, 3, 6].
The link above is a GeeksforGeeks article. The function name allPaths is this guide's own. The tests sort the list of
paths before comparing.
Think first
- How many moves does every path make? How many of them go down?
- How many paths are there?
- When can a path not go down, or not go right?
Hints
Brute force, and why it fails
There is no shortcut: every path must be written out. Recursion builds each exactly once.
The key insight
With only right and down moves, no path can revisit a cell, so no marking is needed: the two choices at each step are the whole search.
Dry run
| path | 1 |
|---|
The matrix has rows 1 2 3 and 4 5 6. Start at 1.
The plan
function walk(r, c, path):
if (r, c) is the bottom-right: record a copy of path; return
if r + 1 < m: walk(r + 1, c, path + [mat[r + 1][c]])
if c + 1 < n: walk(r, c + 1, path + [mat[r][c + 1]])
walk(0, 0, [mat[0][0]])
Complexity
- Time
O(C(m + n - 2, m - 1) × (m + n))- Space
O(m + n)
One path per way of placing the down moves, each m + n - 1 values long.
Edge cases
- One cell: one path with one value.
- One row or one column: one path.
- Square grids grow fast: a 10 × 10 grid has 48620 paths.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<List<Integer>> allPaths(int[][] mat) {
List<List<Integer>> out = new ArrayList<>();
List<Integer> path = new ArrayList<>();
path.add(mat[0][0]);
walk(mat, 0, 0, path, out);
return out;
}
private void walk(int[][] m, int r, int c, List<Integer> path, List<List<Integer>> out) {
if (r == m.length - 1 && c == m[0].length - 1) { out.add(new ArrayList<>(path)); return; }
if (r + 1 < m.length) { // step down
path.add(m[r + 1][c]);
walk(m, r + 1, c, path, out);
path.remove(path.size() - 1);
}
if (c + 1 < m[0].length) { // step right
path.add(m[r][c + 1]);
walk(m, r, c + 1, path, out);
path.remove(path.size() - 1);
}
}
}C++
class Solution {
public:
vector<vector<int>> allPaths(vector<vector<int>>& mat) {
vector<vector<int>> out;
vector<int> path = {mat[0][0]};
walk(mat, 0, 0, path, out);
return out;
}
void walk(vector<vector<int>>& m, size_t r, size_t c, vector<int>& path, vector<vector<int>>& out) {
if (r == m.size() - 1 && c == m[0].size() - 1) { out.push_back(path); return; }
if (r + 1 < m.size()) { // step down
path.push_back(m[r + 1][c]);
walk(m, r + 1, c, path, out);
path.pop_back();
}
if (c + 1 < m[0].size()) { // step right
path.push_back(m[r][c + 1]);
walk(m, r, c + 1, path, out);
path.pop_back();
}
}
};Python
class Solution:
def allPaths(self, mat: list[list[int]]) -> list[list[int]]:
R, C = len(mat), len(mat[0])
out = []
def walk(r: int, c: int, path: list) -> None:
if r == R - 1 and c == C - 1:
out.append(path[:])
return
if r + 1 < R: # step down
path.append(mat[r + 1][c])
walk(r + 1, c, path)
path.pop()
if c + 1 < C: # step right
path.append(mat[r][c + 1])
walk(r, c + 1, path)
path.pop()
walk(0, 0, [mat[0][0]])
return outCommon mistakes
- Forgetting the first cell's value.
- Recording the shared path list instead of a copy.
- Allowing left or up moves, which this problem forbids.