- 矩阵中的最长递增路径
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0){
return 0;
}
visited = new boolean[matrix.length][matrix[0].length];
memo = new int[matrix.length][matrix[0].length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
max = Math.max(max,dfs(matrix,i,j) );
}
}
return max;
}
int[][] dire = new int[][]{
{0,1},{0,-1},{1,0},{-1,0}
};
boolean[][] visited;
int max = 0;
int[][] memo ;
public int dfs(int[][] matrix ,int x,int y){
if (memo[x][y] != 0){
return memo[x][y];
}
++memo[x][y];
for (int[] dir : dire){
int newx = x + dir[0];
int newy = y + dir[1];
if (newx >= 0 && newy >= 0 && newx < matrix.length && newy < matrix[0].length && matrix[newx][newy] > matrix[x][y]){
memo[x][y] = Math.max(memo[x][y],1 + dfs(matrix,newx,newy));
}
}
return memo[x][y];
}