Find the longest strictly increasing route through orthogonally adjacent cells in a matrix.
Problem
Input. A rectangular integer matrix, possibly empty.
Output. Return the maximum number of cells in a path whose value strictly increases at every move.
Rules. Start at any cell and move only up, down, left, or right within the matrix. Diagonal moves and equal-valued moves are forbidden. Count cells, not edges, and preserve the matrix. Empty input returns zero.
Example. For [[9, 9, 4], [6, 6, 8], [2, 1, 1]], return 4.
One path follows values 1 -> 2 -> 6 -> 9 through adjacent cells.
Picture
For [[3,4,5],[2,1,6]], draw an arrow from each cell to each larger orthogonal neighbor.
The longest route follows values 1,2,3,4,5,6, using six distinct cells.
A cycle would require strict increases back to the starting value, making that value larger than itself. Thus no path-local visited set is needed. A continuation cannot revisit its caller’s smaller-valued prefix.
Define as the longest increasing path starting at coordinate , including that cell. A peak returns one. Otherwise choose the largest among its larger neighbors.
| Completed return | Cached length | Reason |
|---|---|---|
(1,2), value 6 | 1 | No larger neighbor |
(0,2), value 5 | 2 | One plus 6’s suffix |
(0,1), value 4 | 3 | One plus 5’s suffix |
(0,0), value 3 | 4 | One plus 4’s suffix |
(1,0), value 2 | 5 | Reuse 3’s completed suffix |
(1,1), value 1 | 6 | Best among neighbors 4, 6 and 2 |
The memo becomes [[4,3,2],[5,6,1]]. A cached value means a completed answer, not merely a discovered cell.
Global flood-fill marks would wrongly suppress valid reuse by other callers.
Coordinate alone identifies the suffix because the immutable matrix fixes every legal continuation. Create the cache inside each call. Sharing it across changed matrices would reuse answers from the wrong graph.
Equal-valued neighbors have no edge. Changing > to >= permits cycles and invalidates this reasoning.
Problem trace
Cache each increasing suffix so later starting points can reuse it
Original matrix and DFS cursor
- DFS cursor
- (0, 0)
- memo
- [.,.,.; .,.,.]
- dependency
- 3 -> 4
Original matrix and DFS cursor
- DFS cursor
- (0, 0)→(0, 2)
- call stack
- not shown→3 -> 4 -> 5
- dependency
- 3 -> 4→5 -> 6
Original matrix and DFS cursor
- DFS cursor
- (0, 2)→(1, 2)
- memo
- [.,.,.; .,.,.]→[.,.,.; .,.,1]
- arithmetic
- not shown→best(6) = 1
Original matrix and DFS cursor
- DFS cursor
- (1, 2)→(0, 2)
- memo
- [.,.,.; .,.,1]→[.,.,2; .,.,1]
- arithmetic
- best(6) = 1→L(0,2) = max(1, 1 + memo[1,2]) = 2
Original matrix and DFS cursor
- DFS cursor
- (0, 2)→(0, 0)
- memo
- [.,.,2; .,.,1]→[4,3,2; .,.,1]
- arithmetic
- L(0,2) = max(1, 1 + memo[1,2]) = 2→best(4)=3; best(3)=4
Original matrix and DFS cursor
- DFS cursor
- (0, 0)→(1, 0)
- memo
- [4,3,2; .,.,1]→[4,3,2; 5,.,1]
- cache hit
- not shown→memo[0,0] = 4
Original matrix and DFS cursor
- DFS cursor
- (1, 0)→(1, 1)
- memo
- [4,3,2; 5,.,1]→[4,3,2; 5,6,1]
- dependencies
- not shown→1 -> 4, 1 -> 6, 1 -> 2
Original matrix and DFS cursor
- path
- not shown→(1,1)->(1,0)->(0,0)->(0,1)->(0,2)->(1,2)
- result
- not shown→6
- dependencies
- 1 -> 4, 1 -> 6, 1 -> 2→not shown
- Recognize it
- Use memoized DFS when every cell asks for an optimal path through neighboring states and a strict monotone move rule prevents cycles.
- Keep true
- Once path_from(r,c) returns, its memo value is the longest increasing path starting at that cell; every candidate is 1 plus an already correct recursively computed larger-neighbor suffix.
- Reuse it
- A strict ranking function can turn implicit neighbor moves into a DAG; memoize the optimal suffix at each state and combine it from higher-ranked neighbors.
Reference drawing
Problem trace
Cache each increasing suffix so later starting points can reuse it
Execution trace
Original matrix and DFS cursor
- DFS cursor
- (0, 0)
- memo
- [.,.,.; .,.,.]
- dependency
- 3 -> 4
Original matrix and DFS cursor
- DFS cursor
- (0, 0)→(0, 2)
- call stack
- not shown→3 -> 4 -> 5
- dependency
- 3 -> 4→5 -> 6
Original matrix and DFS cursor
- DFS cursor
- (0, 2)→(1, 2)
- memo
- [.,.,.; .,.,.]→[.,.,.; .,.,1]
- arithmetic
- not shown→best(6) = 1
Original matrix and DFS cursor
- DFS cursor
- (1, 2)→(0, 2)
- memo
- [.,.,.; .,.,1]→[.,.,2; .,.,1]
- arithmetic
- best(6) = 1→L(0,2) = max(1, 1 + memo[1,2]) = 2
Original matrix and DFS cursor
- DFS cursor
- (0, 2)→(0, 0)
- memo
- [.,.,2; .,.,1]→[4,3,2; .,.,1]
- arithmetic
- L(0,2) = max(1, 1 + memo[1,2]) = 2→best(4)=3; best(3)=4
Original matrix and DFS cursor
- DFS cursor
- (0, 0)→(1, 0)
- memo
- [4,3,2; .,.,1]→[4,3,2; 5,.,1]
- cache hit
- not shown→memo[0,0] = 4
Original matrix and DFS cursor
- DFS cursor
- (1, 0)→(1, 1)
- memo
- [4,3,2; 5,.,1]→[4,3,2; 5,6,1]
- dependencies
- not shown→1 -> 4, 1 -> 6, 1 -> 2
Original matrix and DFS cursor
- path
- not shown→(1,1)->(1,0)->(0,0)->(0,1)->(0,2)->(1,2)
- result
- not shown→6
- dependencies
- 1 -> 4, 1 -> 6, 1 -> 2→not shown
- Recognize it
- Use memoized DFS when every cell asks for an optimal path through neighboring states and a strict monotone move rule prevents cycles.
- Keep true
- Once path_from(r,c) returns, its memo value is the longest increasing path starting at that cell; every candidate is 1 plus an already correct recursively computed larger-neighbor suffix.
- Reuse it
- A strict ranking function can turn implicit neighbor moves into a DAG; memoize the optimal suffix at each state and combine it from higher-ranked neighbors.
Code
from functools import cache
def longest_increasing_path(matrix: list[list[int]]) -> int:
if not matrix or not matrix[0]:
return 0
@cache
def path_from(row: int, col: int) -> int:
best = 1
for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
new_row = row + row_step
new_col = col + col_step
if 0 <= new_row < len(matrix) and 0 <= new_col < len(matrix[0]):
if matrix[new_row][new_col] > matrix[row][col]:
best = max(best, 1 + path_from(new_row, new_col))
return best
return max(
path_from(row, col)
for row in range(len(matrix))
for col in range(len(matrix[0]))
)
Cost: time and space.
Each coordinate computes once and checks four neighbors. Cache size and maximum recursive depth can both reach .
Python can raise RecursionError on a long valid chain; linear total work does not prevent that failure.
Change Evaluation or Aggregation
Start from longest_increasing_path. Preserve strict growth while changing how completed states are obtained or combined.
-
Avoid recursive depth.
New task: Support increasing chains longer than Python’s call-stack limit.
Picture and change: Count incoming edges from smaller neighbors. Use zero-indegree elimination in frozen batches. A cell becomes ready after its last predecessor, so its layer is one plus the maximum predecessor layer. This measures length ending there; the global maximum matches the source’s starting-length maximum.
Code: Complete replacement:
from collections import deque def increasing_path_layers(matrix): if not matrix or not matrix[0]: return 0 rows, columns = len(matrix), len(matrix[0]) steps = ((1, 0), (-1, 0), (0, 1), (0, -1)) degree = [[0] * columns for _ in range(rows)] for row in range(rows): for column in range(columns): degree[row][column] = sum( 0 <= row + row_step < rows and 0 <= column + col_step < columns and matrix[row + row_step][column + col_step] < matrix[row][column] for row_step, col_step in steps ) frontier = deque( (row, column) for row in range(rows) for column in range(columns) if degree[row][column] == 0 ) layers = 0 while frontier: layers += 1 for _ in range(len(frontier)): row, column = frontier.popleft() for row_step, col_step in steps: new_row, new_col = row + row_step, column + col_step if 0 <= new_row < rows and 0 <= new_col < columns: if matrix[new_row][new_col] > matrix[row][column]: degree[new_row][new_col] -= 1 if degree[new_row][new_col] == 0: frontier.append((new_row, new_col)) return layersCheck: The six-cell example returns six.
[[1,1]]returns one, not two.Use when: Recursion depth is a risk. Work and degree/frontier storage remain without recursive calls.
-
Count every increasing path.
New task: Count all nonempty coordinate paths, not just the longest length.
Picture and change: Process cells by increasing value. Each has one singleton path plus paths ending at its smaller neighbors. Sum those ending counts. Equal values create no dependency, regardless of their sorting order.
Code: Complete replacement:
def count_increasing_paths(matrix): if not matrix or not matrix[0]: return 0 rows, columns = len(matrix), len(matrix[0]) counts = [[0] * columns for _ in range(rows)] cells = sorted( (matrix[row][column], row, column) for row in range(rows) for column in range(columns) ) for value, row, column in cells: counts[row][column] = 1 for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)): new_row, new_col = row + row_step, column + col_step if 0 <= new_row < rows and 0 <= new_col < columns: if matrix[new_row][new_col] < value: counts[row][column] += counts[new_row][new_col] return sum(map(sum, counts))Check:
[[1,2]]has three paths:[1],[2],[1,2].[[1,1]]has two singletons.Use when: Multiplicity replaces length. For , sorting costs ; storage is . Exact counts can grow large, so arithmetic cost also depends on integer bit lengths.
Rebuild State Sufficiency
Why can another caller reuse the same coordinate’s suffix?
Answer: Strict growth prevents reentering its smaller prefix. The unchanged matrix, not the caller’s route, determines every legal continuation.