LeetCode #329 Hard

Longest Increasing Path in a Matrix

Longest Increasing Path in a Matrix is LeetCode 329 (Hard). Given an m × n grid of integers, return the length of the longest path in which every step moves up, down, left or right to a cell with a strictly larger value.

Diagonal moves are not allowed, the path may not leave the grid, and its length counts cells, so a single cell is a path of length 1.

Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2³¹ - 1
matrixdfsmemoization
Open on LeetCode ↗
02

Intuition

Let dfs(r, c) be the longest climbing path that starts at cell (r, c). It is 1 plus the best dfs among the larger neighbours, or just 1 if no neighbour is larger.

The key fact is that a strictly increasing path can never return to a cell: getting back would need a step down. So the grid has no cycles, every dfs(r, c) has one fixed answer, and that answer can be cached the first time it is computed. With the cache, each of the m·n cells is solved once, instead of once for every path that passes through it.

03

Approach

1

Write the recursive rule

dfs(r, c) starts at best = 1 for the cell itself. For each of the four neighbours that is inside the grid and holds a larger value, set best = max(best, 1 + dfs(neighbour)).

2

Cache every finished cell

Store dfs(r, c) the first time it returns and reuse it on every later call. The value cannot depend on how you reached the cell, because the path ahead only moves to larger values, never back to where you came from.

3

Try every cell as the start

The longest path can begin anywhere, so call dfs on every cell and return the largest result. Most of those calls hit the cache, so this loop adds almost no work.

4

Watch the recursion depth

A grid whose values climb in one long snake makes the recursion as deep as the number of cells, up to 40,000. In Python raise the limit with sys.setrecursionlimit, or use the layer-peeling BFS shown below, which has no recursion at all.

04

Code in Python, C++ and Java

▶1import sys
▶2from functools import cache
▶3from typing import List
▶4 
▶5 
▶6class Solution:
▶7 def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
▶8 sys.setrecursionlimit(50000)
▶9 rows, cols = len(matrix), len(matrix[0])
▶10 
▶11 @cache
▶12 def dfs(r: int, c: int) -> int:
▶13 best = 1
▶14 for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
▶15 nr, nc = r + dr, c + dc
▶16 if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
▶17 best = max(best, 1 + dfs(nr, nc))
▶18 return best
▶19 
▶20 return max(dfs(r, c) for r in range(rows) for c in range(cols))
matrix994668211waiting callsnoneno cell solved yet
cells93 rows × 3 columns
Each cell gets one number: the longest climbing path that starts there. Moving only to a strictly larger neighbour means a path can never come back to a cell, so there are no cycles and each cell's number never changes once found. That is what makes caching safe.
matrix9path 194668211waiting callsnoneno neighbour is bigger than 9 → path 1
cell9row 0, column 0
waiting calls0
None of the up to four neighbours holds a larger value, so the path cannot leave this cell. It still counts itself, so its number is 1, not 0.
matrix9path 19path 14668211waiting callsnoneno neighbour is bigger than 9 → path 1
cell9row 0, column 1
waiting calls0
None of the up to four neighbours holds a larger value, so the path cannot leave this cell. It still counts itself, so its number is 1, not 0.
matrix9path 19path 14668path 1211waiting calls4 (row 0, col 2)no neighbour is bigger than 8 → path 1
cell8row 1, column 2
waiting calls1
None of the up to four neighbours holds a larger value, so the path cannot leave this cell. It still counts itself, so its number is 1, not 0.
matrix9path 19path 14668path 1211waiting calls4 (row 0, col 2)9 is already solved → reuse path 1
cell9row 0, column 1
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 2668path 1211waiting callsnone4 climbs to 8 → path 2
cell4row 0, column 2
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 8 with a path of 1, so the path from 4 is that plus this cell: 2. The arrow shows the step it takes.
matrix9path 19path 14path 2668path 1211waiting calls6 (row 1, col 0)9 is already solved → reuse path 1
cell9row 0, column 0
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 268path 1211waiting callsnone6 climbs to 9 → path 2
cell6row 1, column 0
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 9 with a path of 1, so the path from 6 is that plus this cell: 2. The arrow shows the step it takes.
matrix9path 19path 14path 26path 268path 1211waiting calls6 (row 1, col 1)9 is already solved → reuse path 1
cell9row 0, column 1
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 268path 1211waiting calls6 (row 1, col 1)8 is already solved → reuse path 1
cell8row 1, column 2
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 1211waiting callsnone6 climbs to 9 → path 2
cell6row 1, column 1
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 9 with a path of 1, so the path from 6 is that plus this cell: 2. The arrow shows the step it takes.
matrix9path 19path 14path 26path 26path 28path 1211waiting callsnone8 is already solved → reuse path 1
cell8row 1, column 2
waiting calls0
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 1211waiting calls2 (row 2, col 0)6 is already solved → reuse path 2
cell6row 1, column 0
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 12path 311waiting callsnone2 climbs to 6 → path 3
cell2row 2, column 0
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 6 with a path of 2, so the path from 2 is that plus this cell: 3. The arrow shows the step it takes.
matrix9path 19path 14path 26path 26path 28path 12path 311waiting calls1 (row 2, col 1)6 is already solved → reuse path 2
cell6row 1, column 1
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 12path 311waiting calls1 (row 2, col 1)2 is already solved → reuse path 3
cell2row 2, column 0
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 12path 31path 41waiting callsnone1 climbs to 2 → path 4
cell1row 2, column 1
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 2 with a path of 3, so the path from 1 is that plus this cell: 4. The arrow shows the step it takes.
matrix9path 19path 14path 26path 26path 28path 12path 31path 41waiting calls1 (row 2, col 2)8 is already solved → reuse path 1
cell8row 1, column 2
waiting calls1
This cell was finished earlier, so its number is read from the cache instead of searching again. Without the cache, every path passing through this cell would redo the whole search below it, which is what makes plain DFS exponential.
matrix9path 19path 14path 26path 26path 28path 12path 31path 41path 2waiting callsnone1 climbs to 8 → path 2
cell1row 2, column 2
waiting calls0
Every larger neighbour has been asked for its own number. The best one is 8 with a path of 1, so the path from 1 is that plus this cell: 2. The arrow shows the step it takes.
matrix9path 19path 14path 26path 26path 28path 12path 31path 41path 2waiting callsnoneanswer: 4, climbing 1 → 2 → 6 → 9
answer4largest number in any cell
Answer 4. The longest path can start anywhere, so the answer is the largest number over all cells. Following the arrows from that cell spells out the path itself. Every cell was solved exactly once, so the work is one visit per cell with four neighbour checks each.
05

Peel layers with BFS

Count, for every cell, how many neighbours are larger. Cells with a count of 0 are peaks: no path can continue from them, so they form the first layer. Remove a layer, lower the counts of the smaller neighbours of its cells, and any cell whose count drops to 0 joins the next layer. The longest path visits one cell per layer, so the number of layers is the answer.

▶1from collections import deque
▶2from typing import List
▶3 
▶4 
▶5class Solution:
▶6 def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
▶7 rows, cols = len(matrix), len(matrix[0])
▶8 dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
▶9 higher = [[0] * cols for _ in range(rows)]
▶10 for r in range(rows):
▶11 for c in range(cols):
▶12 for dr, dc in dirs:
▶13 nr, nc = r + dr, c + dc
▶14 if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
▶15 higher[r][c] += 1
▶16 layer = deque((r, c) for r in range(rows) for c in range(cols) if higher[r][c] == 0)
▶17 layers = 0
▶18 while layer:
▶19 layers += 1
▶20 for _ in range(len(layer)):
▶21 r, c = layer.popleft()
▶22 for dr, dc in dirs:
▶23 nr, nc = r + dr, c + dc
▶24 if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] < matrix[r][c]:
▶25 higher[nr][nc] -= 1
▶26 if higher[nr][nc] == 0:
▶27 layer.append((nr, nc))
▶28 return layers
06

Common pitfalls

Allowing equal neighbours

✗ Wrong
if matrix[nr][nc] >= matrix[r][c]:
✓ Right
if matrix[nr][nc] > matrix[r][c]:

The path must strictly increase. Worse, with >= two equal neighbours call each other back and forth: on [[7, 7]] the recursion overflows the stack instead of returning 1.

Adding a visited set

✗ Wrong
if (r, c) in visited:
    return 0
✓ Right
@cache
def dfs(r, c):

Strict climbing already prevents revisits, so a visited set adds nothing. A global one is wrong: a cell finished on one path is then treated as blocked for the next, and [[1, 2], [4, 3]] returns less than 4.

Running DFS without the cache

✗ Wrong
def dfs(r, c):  # no @cache
✓ Right
@cache
def dfs(r, c):

The answer stays correct, but every path recomputes everything below it. A 200 × 200 grid where values grow towards one corner has an exponential number of climbing paths and times out.

07

Edge cases

All values equal, e.g. [[7, 7], [7, 7]]

No move is allowed, so every cell scores 1 and the answer is 1.

08

Complexity

Time
O(m·n)
Space
O(m·n)
Each cell is solved once and checks four neighbours. The cache takes m·n entries, and the recursion stack can also reach m·n on a snake-shaped grid.
09

Longest Increasing Path in a Matrix FAQ

Why does caching work here when it fails for longest paths in general graphs?

In a graph with cycles, the best path from a node depends on which nodes the path has already used, so one cached number per node is not enough. Here a climbing path can never reach a used cell again, because that would need a step down. The grid is a directed acyclic graph, and in such a graph the longest path from a node is a fixed value.

Can I start the search only from the smallest cells?

Yes. A longest path can always be extended backwards until it starts at a cell with no smaller neighbour, so starting from those cells is enough. With the cache it saves little, because calls on other cells are cheap cache hits anyway.