Problem overview
The method longestIncreasingPath(matrix) gets a grid of numbers, a list of rows, and returns the number of cells on its longest increasing path. A path can start in any cell. Each step moves up, down, left or right, never diagonally and never off the grid. In an increasing path every step goes to a strictly bigger number, so equal numbers block a step.
In the grid [[1, 2, 3], [8, 9, 4], [7, 6, 5]] the path starts at 1, walks around the edge through 2, 3, 4, 5, 6, 7 and 8, and then steps into the middle, to 9. It uses all 9 cells. In [[1, 2, 2, 3]] the two 2s are neighbours, but a path can't step from one to the other, so the longest paths are 1 → 2 and 2 → 3, with 2 cells. In [[9, 8], [2, 7]] the path is 2 → 7 → 8 → 9: right, up, then left. The function returns:
[[1, 2, 3], [8, 9, 4], [7, 6, 5]] 9
[[1, 2, 2, 3]] 2
[[9, 8], [2, 7]] 4
[[5]] 1
[[3, 3], [3, 3]] 1
Approach: longest path from each cell, stored once
Define longest(cell) as the number of cells on the longest increasing path that starts at that cell. It equals 1 plus the best value among the neighbours that hold a bigger number, or just 1 when no neighbour is bigger. The answer is the biggest value over all starting cells.
Computing this with plain recursion repeats a lot of work, because many paths pass through the same cell and each time the longest path from it is worked out again. But the longest path from a cell never depends on how you got there, so it can be stored the first time. With the stored values every cell is worked out once and looks at its 4 neighbours, so the whole search takes O(m · n) time for an m by n grid.
There is no need for a "visited" set. An increasing path never returns to a cell, because each step goes to a strictly bigger number. So the recursion can't loop, and the memo can be shared by all starting points.
Step by step
In longestIncreasingPath:
- Create
memo, a grid of zeros of the same size:[[0] * len(matrix[0]) for _ in range(len(matrix))]. A 0 means "not worked out yet", since every path has at least 1 cell. - Set
result = 0, the longest path found so far. - Visit every cell with two loops, over
rowinrange(len(matrix))andcolinrange(len(matrix[0])). In the inner loop, setresulttomax(result, self.longestFrom(matrix, memo, row, col, -1)). The last argument,prev, is the value of the cell the path comes from. For a starting cell there is none, and -1 is below every number in the grid. - Return
result.
The helper longestFrom(self, matrix, memo, row, col, prev) returns the longest path that starts at (row, col), or 0 when the path can't step onto it:
- Return 0 if the cell is off the grid:
rowbelow 0 or at leastlen(matrix), orcolbelow 0 or at leastlen(matrix[0]). Checking here keeps the loop over neighbours simple. - Return 0 if
matrix[row][col] <= prev. The step must go to a bigger number, and equal numbers are blocked too. - If
memo[row][col] > 0, return it: this cell is already worked out. - Set
best = 0and make a list of the four moves,[-1, 0],[1, 0],[0, -1]and[0, 1]. For each pairdr, dc, setbestto the larger ofbestandself.longestFrom(matrix, memo, row + dr, col + dc, matrix[row][col]). The call itself checks that the neighbour exists and is bigger. - Store
best + 1inmemo[row][col]and return it. A cell with no bigger neighbour gets 1.
For the grid [[9, 8], [2, 7]], calling longestFrom on the cells in turn fills the memo step by step:
longestFrom at (0, 0) -> 1, memo [[1, 0], [0, 0]]
longestFrom at (1, 0) -> 4, memo [[1, 2], [4, 3]]
longestFrom at (1, 1) -> 3, memo [[1, 2], [4, 3]]
longestFrom at (0, 1) -> 2, memo [[1, 2], [4, 3]]
The cell 9 has no bigger neighbour, so it gets 1. Starting at 2, the recursion fills in 7, 8 and 9 on the way, and the memo is complete with one call. The remaining cells are answered from the memo.
The solution in Python
class Solution:
def longestFrom(self, matrix, memo, row, col, prev):
if row < 0 or row >= len(matrix) or col < 0 or col >= len(matrix[0]):
return 0
if matrix[row][col] <= prev:
return 0
if memo[row][col] > 0:
return memo[row][col]
best = 0
directions = [[-1, 0], [1, 0], [0, -1], [0, 1]]
for dr, dc in directions:
best = max(best, self.longestFrom(matrix, memo, row + dr, col + dc, matrix[row][col]))
memo[row][col] = best + 1
return memo[row][col]
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
memo = [[0] * len(matrix[0]) for _ in range(len(matrix))]
result = 0
for row in range(len(matrix)):
for col in range(len(matrix[0])):
result = max(result, self.longestFrom(matrix, memo, row, col, -1))
return result
Python details:
- Bounds are checked by hand. A negative index doesn't raise an error in Python:
matrix[-1]is the last row. So the check forrow < 0andcol < 0is essential, not a formality. - Separate rows in
memo.[[0] * n] * mwould repeat one row, and writing one cell would change the same column in every row. The comprehension makes a new row each time. - Tuple unpacking.
for dr, dc in directionsunpacks each two-item list into two names. - The memo is never reset. It is filled during the first starting cell's recursion and reused by the rest, so the loops over rows and columns cost O(m · n) calls in total.
- Recursion depth. The depth is at most the length of the longest path, up to 1,000 cells here. Python's default limit is about 1,000 nested calls, so in a file of your own a path that long needs
sys.setrecursionlimitraised first.
Complexity
Each of the m · n cells is worked out once, looking at 4 neighbours, and later visits return from the memo at once. The time is O(m · n). The memo takes O(m · n) space, and the recursion is as deep as the longest path.
Edge cases and common mistakes
- Allowing equal values. If the test is
< previnstead of<= prev, a step between two equal cells is allowed, and the path can bounce between them forever. On[[1, 2, 2, 3]]that version raises aRecursionError. - One cell.
[[5]]returns 1, and a grid where all cells are equal, such as[[3, 3], [3, 3]], also returns 1. - Using 0 as "unknown" when a path could be 0. A path always has at least one cell, so a stored value is at least 1 and 0 is safe as the marker.
- Starting only from the top-left. The best path can start anywhere, so the answer must be the maximum over every starting cell, as in the example
[[9, 8], [2, 7]], where the best path starts at the bottom-left. - Diagonal moves. Only the four directions are allowed.
In the editor above, try a single row such as [[1, 2, 3, 4]] (4) and the third example (4).
