原题:这里写链接内容
分析:这道题很容易想到DFS的做法,于是写成了代码1,但是TLE,其实也很正常,因为在遍历过程中可能多次经历了某些中间状态。而这些状态实际上只需要访问一次就可以了,于是又写出了代码2,DFS+动态规划。
第一版:
public class Solution {
int[][] matrix;
int matrixRow;
int matrixCol;
public int longestIncreasingPath(int[][] matrix) {
this.matrix = matrix;
int maxCount = 0;
matrixRow = matrix.length;
if(matrixRow == 0)
return 0;
matrixCol = matrix[0].length;
for(int row = 0;row<matrixRow;row++){
for(int col = 0;col<matrixCol;col++){
int count = dfs(row,col,1);
if(count > maxCount)
maxCount = count;
}
}
return maxCount;
}
private int dfs(int row,int col,int count){
int tmpCount = 0;
int[] rows = {-1,1,0,0};
int[] cols = {0,0,-1,1};
for(int i = 0;i<rows.length;i++){
int currentRow = row+rows[i];
int currentCol = col+cols[i];
if(currentRow<0 || currentRow>=matrixRow)
continue;
if(currentCol<0 || currentCol>=matrixCol)
continue;
if(matrix[currentRow][currentCol] > matrix[row][col])
tmpCount = Math.max(tmpCount,dfs(currentRow,currentCol,count+1));
}
return Math.max(count,tmpCount);
}
}
第二版
public class Solution {
int[][] matrix;
int[][] countMatrix;
int matrixRow;
int matrixCol;
int res = 0;
public int longestIncreasingPath(int[][] matrix) {
this.matrix = matrix;
matrixRow = matrix.length;
if(matrixRow <= 0)
return 0;
matrixCol = matrix[0].length;
countMatrix = new int[matrixRow][matrixCol];
initCountMatrix();
for(int i = 0;i<matrixRow;i++){
for(int j = 0;j<matrixCol;j++){
dfs(i,j);
}
}
return res;
}
private void dfs(int row,int col){
int[] rows = {-1,1,0,0};
int[] cols = {0,0,-1,1};
int count = 1;
for(int i = 0;i<4;i++){
int tmpRow = row+rows[i];
int tmpCol = col+cols[i];
if(tmpRow < 0 || tmpRow >= matrixRow)
continue;
if(tmpCol < 0 || tmpCol >= matrixCol)
continue;
if(matrix[tmpRow][tmpCol] > matrix[row][col]){
if(countMatrix[tmpRow][tmpCol] == -1){
dfs(tmpRow,tmpCol);
}
count = Math.max(count,countMatrix[tmpRow][tmpCol]+1);
}
}
countMatrix[row][col] = count;
res = Math.max(res,count);
}
private void initCountMatrix(){
for(int i = 0;i<matrixRow;i++){
for(int j = 0;j<matrixCol;j++)
countMatrix[i][j] = -1;
}
}
}