package com.company.test.矩阵最长递增路径;
import java.util.Map;
/**
* @author xienl
* @description 矩阵最长递增路径
* @date 2022/9/6
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
int m , n;
int[][] dirs = {{-1, 0}, {1, 0}, {0 , -1}, {0 , 1}};
public int solve (int[][] matrix) {
if (matrix.length == 0 || matrix[0].length == 0){
return 0;
}
m = matrix.length;
n = matrix[0].length;
int res = 0;
int[][] dp = new int[m][n];
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
res = Math.max(res, dfs(matrix, dp, i , j));
}
}
return res;
}
private int dfs(int[][] matrix, int[][] dp , int row, int col){
if (dp[row][col] != 0){
return dp[row][col];
}
dp[row][col]++;
for (int i = 0; i < 4; i++){
int nextRow = row + dirs[i][0];
int nextCol = col + dirs[i][1];
if (nextRow >= 0 && nextRow < m && nextCol >= 0 && nextCol < n && matrix[nextRow][nextCol] > matrix[row][col]){
dp[row][col] = Math.max(dp[row][col], dfs(matrix, dp, nextRow, nextCol) + 1);
}
}
return dp[row][col];
}
}
牛客网:NC138 矩阵最长递增路径
最新推荐文章于 2024-07-25 14:21:47 发布