Python 0329.py
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
width = len(matrix[0])
height = len(matrix)
todo = set()
for x in range(width):
for y in range(height):
todo.add(tuple([ x, y ]))
longest = 0
while todo:
longest += 1
next = set()
for x,y in list(todo):
current = matrix[y][x]
if x > 0 and matrix[y][x-1] > current:
next.add(tuple([ x-1, y ]))
if x < width - 1 and matrix[y][x+1] > current:
next.add(tuple([ x+1, y ]))
if y > 0 and matrix[y-1][x] > current:
next.add(tuple([ x, y-1 ]))
if y < height - 1 and matrix[y+1][x] > current:
next.add(tuple([ x, y+1 ]))
todo = next
return longest
Difficulty
and has an acceptance rate of about 54% (900k+ submissions).
Typical patterns to solve this problem:
- Array
- Breadth First Search
- Depth First Search
- Dynamic Programming
- Graph
- Matrix
- Memoization
- Topological Sort
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The implementation computes the length of the longest strictly increasing path that can be formed by moving horizontally or vertically across a two-dimensional integer grid. It treats each cell as a potential starting point, iteratively expands the frontier of cells that can be reached by a longer increasing sequence, and counts how many expansion steps are required before no further moves are possible. The final count corresponds to the length of the longest increasing path.
Initialization
The code first extracts the dimensions of the matrix:
width = len(matrix[0])
height = len(matrix)
A set named todo is populated with a tuple for every coordinate pair (x, y) in the grid:
todo = set()
for x in range(width):
for y in range(height):
todo.add(tuple([ x, y ]))
Using a set guarantees that each coordinate appears only once and enables fast membership checks and updates during the expansion phases.
Main Loop
The variable longest is initialized to zero and serves as a counter for the number of expansion rounds performed. The loop continues while the todo set is non-empty:
longest = 0
while todo:
longest += 1
next = set()
...
todo = next
Each iteration represents one additional step in the increasing path, and the loop terminates when no cell can be extended further.
Neighbor Exploration
Inside the loop, the algorithm iterates over a snapshot of the current frontier (list(todo)) to avoid modification during iteration. For each cell (x, y), it retrieves the current value:
current = matrix[y][x]
It then checks the four orthogonal neighbors. If a neighbor exists within bounds and its value is strictly greater than current, that neighbor is added to the next set, indicating it can be reached in the next expansion step:
if x > 0 and matrix[y][x-1] > current:
next.add(tuple([ x-1, y ]))
if x < width - 1 and matrix[y][x+1] > current:
next.add(tuple([ x+1, y ]))
if y > 0 and matrix[y-1][x] > current:
next.add(tuple([ x, y-1 ]))
if y < height - 1 and matrix[y+1][x] > current:
next.add(tuple([ x, y+1 ]))
By only adding neighbors with larger values, the algorithm enforces the strictly increasing constraint.
Termination
When the todo set becomes empty, the while-loop exits and the method returns the accumulated longest count:
return longest
At this point, no further cells can be added to the frontier, meaning the longest possible increasing sequence has been fully explored.
Edge Cases Handled
The code gracefully handles matrices with a single row or a single column because the boundary checks (x > 0, x < width - 1, y > 0, y < height - 1) automatically prevent out-of-range accesses. A matrix consisting of a single element also works: the initial todo set contains one coordinate, the loop runs once, and the method returns 1, correctly indicating that the longest increasing path consists of the solitary cell. Uniform matrices where all values are equal are processed without error; no neighbor will satisfy the strict greater-than condition, so the frontier collapses after the first iteration, yielding a path length of 1.
Performance Optimizations
Using a set for both the current frontier (todo) and the next frontier (next) provides O(1) average-time operations for insertion and membership testing, which keeps each expansion step efficient even when many cells are involved. Converting todo to a list before iteration (for x, y in list(todo):) avoids the overhead of modifying the set while iterating, ensuring that each cell is examined exactly once per round. The algorithm also avoids recursion or explicit depth-first search, thereby eliminating the risk of stack overflow on large inputs and reducing function-call overhead. By incrementally building the frontier rather than recomputing reachable cells from scratch each time, the implementation reuses previously discovered information and limits the amount of work performed in each iteration.
ELI5 - Simplified Explanation
Imagine a big grid like a hopscotch board where every square has a number drawn on it. The goal is to walk across the board by only stepping on squares that have bigger numbers than the one where you are currently standing.
The code starts by finding all the squares on the board and putting them into a big collection to keep track of where everything is. It then starts a game of moving around. For every single square in the collection, the computer looks left, right, up, and down to see if there is a neighbor with a bigger number. If a neighbor is bigger, that neighbor gets added to a new list for the next turn.
The computer keeps track of how many steps it takes to keep moving to bigger numbers. It keeps going until it runs out of places to step because every neighbor is smaller than where it is standing. The number of turns it took to walk that path is what the code calculates.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| MemoryLimitExceeded | C++ | Python | ||||||||
| Progiez | C++ | Python | Java | |||||||
| github | BigEggStudy | C# | ||||||||
| black-shadows | C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| MemoryLimitExceeded | Python, C++ | |||||||||
| Progiez | C++, Java, Python | |||||||||
| BigEggStudy | C# | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| FelixFan1122 | C# | |||||||||
| fengvyi | C++ | |||||||||
| fpdjsns | C++ | |||||||||
| fsq | C++ | |||||||||
| Garvit244 | Python | |||||||||
| halfrost | Go | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| ruoru | Rust | |||||||||
| shreymehul | C# | |||||||||
| suxrobGM | C# | |||||||||
| trung-hn | Python | |||||||||
| varunu28 | Java | |||||||||
| vli02 | C | |||||||||
| wisdompeak | C++ | |||||||||
| XiaotaoGuo | C++ | |||||||||
| YuriSpiridonov | Python | |||||||||
| zfang399 | C++ |
Videos
Solved On The Same Day
- problem 1218: Longest Arithmetic Subsequence of Given Difference
- problem 1631: Path With Minimum Effort
- problem 332: Reconstruct Itinerary
- problem 1312: Minimum Insertion Steps to Make a String Palindrome
- problem 1964: Find the Longest Valid Obstacle Course at Each Position
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality