Longest Increasing Path in a Matrix

题目链接:https://leetcode.com/problems...

dfs + 记忆化搜索,用一个二维dp记录找到的最长路径的长度,如果发现dpi != 0,证明这个点被找过,不用重复。Number of Islands和这题一个思路。

public class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) return 0;
        // dp[i][j] the longest increasing len from (i, j)
        // enumerate all start position
        // dfs find the longest path, if not in dp[i][j]
        dp = new int[matrix.length][matrix[0].length];
        int global = 0;
        for(int i = 0; i < matrix.length; i++) {
            for(int j = 0; j < matrix[0].length; j++) {
                if(dp[i][j] == 0) {
                    dp[i][j] = dfs(matrix, i, j);
                }
                global = Math.max(global, dp[i][j]);
            }
        }
        return global;
    }
    int[][] dp;
    int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
    private int dfs(int[][] matrix, int x, int y) {
        if(dp[x][y] != 0) return dp[x][y];
        int len = 1;
        for(int i = 0; i < dir.length; i++) {
            int nx = x + dir[i][0], ny = y + dir[i][1];
            if(nx >= 0 && nx < matrix.length && ny >= 0 && ny < matrix[0].length) {
                if(matrix[nx][ny] > matrix[x][y]) len = Math.max(len, dfs(matrix, nx, ny) + 1);
            }
        }
        dp[x][y] = len;
        return len;
    }
}

lulouch13
13 声望6 粉丝