329. Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary (i.e. wrap-around is not allowed).

Example

Input: nums =
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example

Input: nums =
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

题意:这个题是找出最长的上升子序列问题在一个 2D 图里面。 没啥技巧就是暴搜 + memo 如果不加 memo 的话会超时。还有要注意的一点是,既然要找递增的序列,那么需要把当前值以变量的形势传进去。 因为新的坐标不一定合法,也可以在for-loop里面判断,但感觉会比较麻烦。

代码

class Solution {
    public int helper(int[][] matrix, int x, int y, int cur, Set<Integer> set, int[] memo) {
        int m = matrix.length, n = matrix[0].length;
        if(x < 0 || x >= matrix.length || y < 0 || y >= n || set.contains(x * n + y)) return 0;
        if(matrix[x][y] <= cur) return 0;
        if(memo[x * n + y] != -1) return memo[x * n + y];
        int[] dx = new int[]{1, -1, 0, 0};
        int[] dy = new int[]{0, 0, 1, -1};
        int ret = 0;
        for(int i = 0; i < dx.length; i++) {
            int px = x + dx[i], py = y + dy[i];
            set.add(x * n + y);
            ret = Math.max(ret, helper(matrix, px, py, matrix[x][y], set, memo) + 1);
            set.remove(x * n + y);
        }
        memo[x * n + y] = ret;
        return ret;
    }
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0) return 0;
        int m = matrix.length, n = matrix[0].length;
        int ret = 0;
        int[] memo = new int[m * n + n + 5];
        Arrays.fill(memo, -1);
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(memo[i * n + j] == -1) ret = Math.max(ret, helper(matrix, i, j, -1, new HashSet<Integer>(), memo));
            }
        }
        return ret;
    }
}

Search

    Table of Contents