题解 | #矩阵最长递增路径#
矩阵最长递增路径
https://www.nowcoder.com/practice/7a71a88cdf294ce6bdf54c899be967a2
import java.util.*; public class Solution { private int maxPath=0; public int solve (int[][] matrix) { // write code here int row=matrix.length; if(row==0){ return 0; } int col=matrix[0].length; for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ dfs(matrix,i,j,row,col,1); } } return maxPath; } public void dfs(int[][]matrix, int i,int j,int row,int col,int k){ if(i<0||j<0||i>=row||j>=col){ return; } if(i>0){ if(matrix[i-1][j]>matrix[i][j]){ dfs(matrix,i-1,j,row,col,k+1); } } if(j>0){ if(matrix[i][j-1]>matrix[i][j]){ dfs(matrix,i,j-1,row,col,k+1); } } if(i<row-1){ if(matrix[i+1][j]>matrix[i][j]){ dfs(matrix,i+1,j,row,col,k+1); } } if(j<col-1){ if(matrix[i][j+1]>matrix[i][j]){ dfs(matrix,i,j+1,row,col,k+1); } } maxPath=Math.max(maxPath,k); } }