问题:
找到一个二维数组中最长的升序列的长度,序列只可以上下左右走。
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]
- 开始并没有带记录,只是对每一个位置作dfs,超时
- 创建一个mem数组,若算出某个节点开始的最长路径就记录下来。
- 还有一次错是因为二维数组的matrix[0]有可能是null但没有考虑
程序:
public class Solution {
public int dfs(int[][] matrix, int[][] mem, int i, int j, int row, int col) {
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
int lst = 1;
for(int k = 0; k < 4; k++) {
if(i+dx[k] > -1 && i+dx[k] < row && j+dy[k] > -1 && j+dy[k] < col && matrix[i+dx[k]][j+dy[k]] > matrix[i][j]) {
int tmplst;
if(mem[i+dx[k]][j+dy[k]] == 0)
tmplst = dfs(matrix,mem,i+dx[k],j+dy[k],row,col);
else
tmplst = mem[i+dx[k]][j+dy[k]];
if(1+tmplst > lst) lst = 1 + tmplst;
}
}
mem[i][j] = lst;
return lst;
}
public int longestIncreasingPath(int[][] matrix) {
int row = matrix.length;
if(row == 0) return 0;
int col = matrix[0].length;
int longest = 0;
int[][] mem = new int[row][col];
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++) {
if(mem[i][j] == 0) {
int tmp = dfs(matrix, mem, i, j, row, col);
if(tmp > longest) longest = tmp;
}
}
return longest;
}
}