class Solution {
int[][] maxpath;//记录每个节点的最长递增路径
int m , n;
public int dfs(int[][] matrix,int i,int j){
int max = 0;
if(i-1>=0 && matrix[i-1][j] > matrix[i][j]) //上
{
if(maxpath[i-1][j] != 0)
max = Math.max(maxpath[i-1][j],max);
else
max = Math.max(dfs(matrix, i-1, j),max);
}
if(i+1<m && matrix[i+1][j] > matrix[i][j]) //下
{
if(maxpath[i+1][j] != 0)
max = Math.max(maxpath[i+1][j],max);
else
max = Math.max(dfs(matrix, i+1, j),max);
}
if(j-1>=0 && matrix[i][j-1] > matrix[i][j]) //左
{
if(maxpath[i][j-1] != 0)
max = Math.max(maxpath[i][j-1],max);
else
max = Math.max(dfs(matrix, i, j-1),max);
}
if(j+1<n && matrix[i][j+1] > matrix[i][j]) //右
{
if(maxpath[i][j+1] != 0)
max = Math.max(maxpath[i][j+1],max);
else
max = Math.max(dfs(matrix, i, j+1),max);
}
maxpath[i][j] = max + 1;
return maxpath[i][j];
}
public int longestIncreasingPath(int[][] matrix) {
m = matrix.length;
n = matrix[0].length;
int max = 0;
maxpath = new int[m][n];//为已经访问过的节点记录其最长递增路径
for(int i = 0;i < m;i++){
for(int j=0;j<n;j++){
if(maxpath[i][j] ==0)
dfs(matrix,i,j);
max = Math.max(maxpath[i][j],max);
}
}
return max;
}
}