Total Accepted: 9010
Total Submissions: 29883
Difficulty: Hard
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).
Example 1:
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [ [3,4,5], [3,2,6], [2,2,1] ]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
这道题目我使用的dfs+dp,这里dp的实现的方式是使用hashmap存储已经计算过的的节点,然后dfs搜索到已经计算过的结果,直接提取结果。
public class Solution {
HashMap<Integer, Integer> index2lenth=new HashMap<>();
public int Search(int iInex,int jIndex,int[][]matrix){
int row=matrix.length;
int column=matrix[0].length;
if(index2lenth.containsKey(iInex*column+jIndex))
return index2lenth.get(iInex*column+jIndex);
int max=1;
int temp;
if(iInex-1>=0&&matrix[iInex-1][jIndex]<matrix[iInex][jIndex]){
temp=Search(iInex-1, jIndex, matrix);
max=max<(temp+1)?temp+1:max;
}
if(jIndex-1>=0&&matrix[iInex][jIndex-1]<matrix[iInex][jIndex]){
temp=Search(iInex, jIndex-1, matrix);
max=max<(temp+1)?temp+1:max;
}
if(iInex+1<row&&matrix[iInex+1][jIndex]<matrix[iInex][jIndex]){
temp=Search(iInex+1, jIndex, matrix);
max=max<(temp+1)?temp+1:max;
}
if(jIndex+1<column&&matrix[iInex][jIndex+1]<matrix[iInex][jIndex]){
temp=Search(iInex, jIndex+1, matrix);
max=max<(temp+1)?temp+1:max;
}
index2lenth.put(iInex*column+jIndex, max);
return max;
}
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length==0)
return 0;
int max=0;
int row=matrix.length;
int column=matrix[0].length;
for(int i=0;i<row;i++){
for(int j=0;j<column;j++){
if(index2lenth.containsKey(i*column+j)){
int temp=index2lenth.get(i*column+j);
max=max<temp?temp:max;
}
else {
int temp=Search(i,j,matrix);
max=max<temp?temp:max;
}
}
}
return max;
}
}
总觉得有纯dp的方式,尝试了一下,超时了,求指导~
public class Solution {
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length==0)
return 0;
int rowNum=matrix.length;
int column=matrix[0].length;
int[][] lenth=new int[rowNum][column];
for(int i=0;i<rowNum;i++)
for(int j=0;j<column;j++)
lenth[i][j]=1;
int count;
int max=0;
for(int k=0;k<column*rowNum-1;k++){
count=0;
for(int i=0;i<rowNum;i++){
for(int j=0;j<column;j++){
if(i-1>=0&&matrix[i-1][j]<matrix[i][j]){
lenth[i][j]=lenth[i-1][j]+1;
count++;
max=max<lenth[i][j]?lenth[i][j]:max;
}
if(j-1>=0&&matrix[i][j-1]<matrix[i][j]){
lenth[i][j]=lenth[i][j-1]+1;
count++;
max=max<lenth[i][j]?lenth[i][j]:max;
}
if(i+1<rowNum&&matrix[i+1][j]<matrix[i][j]){
lenth[i][j]=lenth[i+1][j]+1;
count++;
max=max<lenth[i][j]?lenth[i][j]:max;
}
if(j+1<column&&matrix[i][j+1]<matrix[i][j]){
lenth[i][j]=lenth[i][j+1]+1;
count++;
max=max<lenth[i][j]?lenth[i][j]:max;
}
}
}
if(count==0)
break;
}
return max;
}
}