Given an integer matrix, find the length of the longest increasing path.
From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).
nums = [
The longest increasing path is [1, 2, 6, 9].
nums = [
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Solve by Backtracking
Ideally, we could check each possible path starting from each possible position in the grid. At each point we have 4 neighbors to walk through. We need to return the maximum length walk among all the walks that goes through 4 neighbors. We will start from a neighbor of (i,j) and backtrack to (i,j) after completion of walk through the neighbor. We will then continue walking to next neighbor.
Now, question is how do we perform the walk and how to make sure that we don’t walk through the same path over and over. This is a classic backtrack problem where we need to do a DFS walk. We will halt the walk through a neighbor if it is not safe i.e. falling out of boundary or not a strictly increasing order path. Each time we perform a walk to a grid position in the path we increase the length of the current path. After we finish a walk we update the max len by using the path length of the current walk.
Ok, we performed the walk through DFS. But how to avoid walking through the same path (or subpath) again and again? Note that, if we already performed a walk starting from grid point(i,j) then any time we come back to the node through a different walk, we can actually skip the walk through (i,j) by caching the result during first walk through this node. That is we can memorize the max length walks using a dp table dp[i][j].
Below is the O(n^2) implementation of the idea described above.