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 are not allowed).
Example 1:
Nums = [ [9, 9,4], [6, 6,8], [2,1, 1]]
Return4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
Nums = [ [3,4,5], [3,2,6], [2,2,1]
Return4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
Analysis:
We can use DFS + memrization.
At Curret Point (i,j), we detect all for directions, find the lips of the 4 neighbor nodes and select the longest one to co NStruct LIP of (I,J). Once We finish, we can record the LIP len of (i,j), so if this len is queried later, we don't need to find it again.
Some notes:
1. We don't need to the record points on current search path, because it's increasing path, no furture point would be one of The points on path.
2. We don't need to record the points on the lips of (i,j), intead, we just need to record the length.
3. We don't need to worry that a neighbor point ' LIP would overlap with the points on current search path, because it is increasing path.
Solution:
1 Public classSolution {2 int[] Xmove =New int[]{1,0,-1,0};3 int[] Ymove =New int[]{0,1,0,-1};4 5 Public intLongestincreasingpath (int[] matrix) {6 if(Matrix.length = = 0 | | matrix[0].length = = 0)7 return0;8 9 int[] Liplen =New int[Matrix.length] [Matrix[0].length];Ten intMaxLen = 0; One for(inti = 0; i < matrix.length; i++) A for(intj = 0; J < Matrix[0].length; J + +) { - intLen =findliprecur (Matrix, Liplen, I, j); - if(MaxLen <len) theMaxLen =Len; - } - - returnMaxLen; + } - + Public intFindliprecur (int[] Matrix,int[] Liplen,intXinty) { A //If current point is already addressed at if(liplen[x][y]! = 0) - returnLiplen[x][y]; - - intMaxLen = 0; - for(inti = 0; i < xmove.length; i++) { - intNEXTX = x +Xmove[i]; in intNexty = y +Ymove[i]; - if(Isfeasible (Matrix, NEXTX, nexty) && matrix[nextx][nexty] >Matrix[x][y]) { to intLen =findliprecur (Matrix, Liplen, NEXTX, nexty); + if(MaxLen <Len) { -MaxLen =Len; the } * } $ }Panax Notoginseng - //Record LIP Len of current Point theLiplen[x][y] = maxlen + 1; + returnMaxLen + 1; A } the + Public BooleanIsfeasible (int[] Matrix,intXinty) { - return(x < matrix.length && x >= 0) && (y < matrix[0].length && y >= 0); $ } $ - -}
Leetcode-longest increasing Path in a Matrix