Longest Increasing Path in a Matrix

Problem:
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 1:
nums = [
  [9,9,4],
  [6,6,8],
  [2,1,1]
]
Return 4
The longest increasing path is [1, 2, 6, 9].
Example 2:
nums = [
  [3,4,5],
  [3,2,6],
  [2,2,1]
]
Return 4
The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Analysis:
被leetcode tag坑了,一开始用topological sort,实现到一半发现有问题。
DFS is easy, but cache is the key. Current path length is the max of its succeeding path + 1.

Solution:

class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        int res = 0;
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return res;
    
        int[][] cache = new int[matrix.length][matrix[0].length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                int length = helper(matrix, cache,i , j, Integer.MAX_VALUE);
                res = Math.max(length, res);
            }
        }   
        return res;
    }
    
    private int helper(int[][] matrix, int[][] cache, int x, int y, int pre) {
        if (x < 0 || x >= matrix.length || y < 0 || y >= matrix[0].length || matrix[x][y] >= pre) {
            return 0;
        }
        
        if (cache[x][y] > 0) {
            return cache[x][y];
        } else {
            int val = matrix[x][y];
            int max = 0;
            max = Math.max(helper(matrix, cache, x + 1, y, val), max);
            max = Math.max(helper(matrix, cache, x - 1, y, val), max);
            max = Math.max(helper(matrix, cache, x, y + 1, val), max);
            max = Math.max(helper(matrix, cache, x, y - 1, val), max);
        
            cache[x][y] = ++max;
            return max;
        }


    } 
}

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List