这道题我用最容易想的想法就是回溯法计算分别延四个方向计算,结果时间复杂度为O(n5),结果导致时间过长
代码如下
public class Solution {
int max = 0;
public int longestIncreasingPath(int[][] matrix) {
for(int i = 0;i <matrix.length;i++){
for(int j = 0;j<matrix[i].length;j++){
go(matrix,i,j,0);
}
}
return max;
}
public void go(int[][] matrix,int i,int j,int pathNum){
pathNum++;
//System.out.println(pathNum);
if(i-1>=0&&matrix[i-1][j] > matrix[i][j])
go(matrix,i-1,j,pathNum);
if(i+1<matrix.length&&matrix[i+1][j] > matrix[i][j])
go(matrix,i+1,j,pathNum);
if(matrix.length>0 && j-1>=0 &&matrix[i][j-1] > matrix[i][j])
go(matrix,i,j-1,pathNum);
if(matrix.length>0 && j+1< matrix[0].length&&matrix[i][j+1]>matrix[i][j])
go(matrix,i,j+1,pathNum);
max = Math.max(pathNum,max);
}
后期看提示改用动态规划做,即
if四个方向由比matrix[i][j]大的则dp[i][j] = max(四个方向比他大的+1);
else dp[i][j] = 1
时间复杂度为O(5n)
代码如下
public class Solution {
int[][] dp;
public int longestIncreasingPath(int[][] matrix) {
if(matrix.length == 0)
return 0;
int max = 0;
dp = new int[matrix.length][matrix[0].length];
for(int i = 0;i <matrix.length;i++){
for(int j = 0;j<matrix[i].length;j++){
max = Math.max(go(matrix,i,j),max);
}
}
return max;
}
public int go(int[][] matrix,int i,int j){
if(dp[i][j]!=0)
return dp[i][j];
dp[i][j] = 1;
if(i-1>=0&&matrix[i-1][j] > matrix[i][j])
dp[i][j] = Math.max(1+go(matrix,i-1,j),dp[i][j]);
if(i+1<matrix.length&&matrix[i+1][j] > matrix[i][j])
dp[i][j] = Math.max(1+go(matrix,i+1,j),dp[i][j]);
if(matrix.length>0 && j-1>=0 &&matrix[i][j-1] > matrix[i][j])
dp[i][j] = Math.max(1+go(matrix,i,j-1),dp[i][j]);
if(matrix.length>0 && j+1< matrix[0].length&&matrix[i][j+1]>matrix[i][j])
dp[i][j] = Math.max(1+go(matrix,i,j+1),dp[i][j]);
return dp[i][j];
}
}
2017/3/5