The Longest Increasing Path in a Matrix is a famous problem where you are given a 2D grid of integers. Your goal is to find the length of the longest path where each subsequent cell's value is strictly greater than the previous cell's value. You can move up, down, left, or right, but you cannot move diagonally, and you cannot wrap around the edges of the matrix.
This is a flagship Hard-level problem asked by companies like Google, Meta, and Uber. It acts as the ultimate test of a candidate's ability to combine Depth-First Search (DFS) with Memoization (Dynamic Programming). A naive DFS will recalculate the same paths repeatedly, resulting in an exponential time limit failure. Interviewers want to see if you can cache results to drastically optimize grid traversal down to .
The definitive pattern is DFS with Memoization (also known as Top-Down Dynamic Programming). You create a 2D cache matrix of the same size as the input, initialized with zeros. You loop through every cell in the grid and initiate a DFS. During the DFS, if you attempt to explore a cell that already has a non-zero value in the cache, you immediately return that cached value instead of exploring it again.
Consider the matrix:
9 9 4
6 6 8
2 1 1
We iterate and run DFS from each cell.
1 (bottom right). It can't go anywhere strictly increasing. Path length = 1. Cache it.1 (bottom middle). It can go right to 1? No, must be strictly greater. It can go up to 6 or left to 2.1 (bottom middle) -> 2 -> 6 -> 9. Length is 4. We save cache[2][1] = 4.2 (bottom left), it looks at 6. The 6 will look at 9. But wait! 6 already explored this and cached its max path. The DFS simply grabs the cached value and adds 1.A very common mistake is trying to keep a visited array (like in standard island-finding algorithms) and un-marking it during backtracking. Because the path must be strictly increasing, it is impossible to loop back onto your own path! Therefore, a visited set is entirely unnecessary and just wastes memory and compute time. The memoization cache itself acts as your history.
To crush the Longest Increasing Path in a Matrix interview question, memorize the structure of a recursive DFS function that returns an integer. Your base case is hitting the edge of the matrix or a cell that isn't strictly greater. Before returning your calculated maximum from the 4 directions, assign it to your cache. This Top-Down DP pattern is universally applicable to many grid-based optimization problems.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Number of Increasing Paths in a Grid | Hard | Solve | |
| Cat and Mouse II | Hard | Solve | |
| Disconnect Path in a Binary Matrix by at Most One Flip | Medium | Solve | |
| Alien Dictionary | Hard | Solve | |
| Sliding Puzzle | Hard | Solve |