Problem 329 · LeetCode 329(opens in a new tab)
Longest Increasing Path in a Matrix
HardDepth-first search
You are given an m × n grid of whole numbers, matrix. A path moves from a cell to the cell above, below, left or right of it, never diagonally and never off the grid.
A path is increasing when every step goes to a strictly bigger number. Return how many cells the longest increasing path visits.
Example 1
Input: matrix = [[5, 6, 1],
[4, 3, 2]]
Output: 6
Why: 1 → 2 → 3 → 4 → 5 → 6 snakes through every cell2 more examples and the constraints
Example 2
Input: matrix = [[2, 2],
[2, 2]]
Output: 1
Why: equal neighbours do not count as increasingExample 3
Input: matrix = [[8, 3, 4],
[7, 1, 9]]
Output: 4
Why: 1 → 3 → 4 → 9Constraints
- The grid has 1 to 200 rows and 1 to 200 columns
- Every value is from 0 up to 2,147,483,647 (2³¹ − 1)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DFS from every cellExponential
- DFS + memoO(m·n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 200 × 200 grid | Verdict |
|---|---|---|---|
| DFS from every cell | Exponential | Times out; only for small grids | |
| DFS + memo | O(m·n) | Best; each cell solved once |
m = rows, n = columns.
Edge cases to test
- All values equal. No move is allowed, so the answer is 1.
- One cell.
[[0]]gives 1: a single cell is a path. - One row or one column. Only two directions exist; bounds checks must still be right.
- Huge values. Values reach 2,147,483,647. Compare them; never add or subtract them, which could overflow.
Common mistakes
- Allowing equal neighbours, which breaks the no-loop guarantee and the answer.
- Keeping a visited set per path: not needed, because increasing paths cannot revisit a cell.
- Using 0 as a memo value that could be a real answer. Every cell has a path of at least 1, so 0 is safe as “not computed”.
How to talk through it
- 1Clarify. Four directions only? Strictly increasing? Is the answer the number of cells?
- 2Give the brute force. DFS from every cell; say why it repeats the same subproblems.
- 3Spot the fixed subproblem. The best path from a cell is the same no matter how you got there, and there are no cycles.
- 4Code the memo DFS. Check memo, try four neighbours, store 1 + best.
- 5Test out loud. Run the all-equal grid and Example 1, and give O(m·n) with the reason.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?