1. 程式人生 > >#leetcode#329. Longest Increasing Path in a Matrix

#leetcode#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 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.


---------------------------------------------------------------------------------------------------------------------------------


這題第一思路是DFS,對於每個點出發都數longest increasing path,程式碼如下

public class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int res = Integer.MIN_VALUE;
        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 max = helper(matrix, i, j, Integer.MIN_VALUE, cache);
                res = Math.max(res, max);
            }
        }
        
        return res;
    }
    
    private int helper(int[][] matrix, int i, int j, int val, int[][]cache){
        if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)
            return 0;
        if(cache[i][j] != 0){
            return cache[i][j];
        }
        if(matrix[i][j] <= val){
            return 0;
        }
        int up = helper(matrix, i - 1, j, matrix[i][j], cache);
        int down = helper(matrix, i + 1, j, matrix[i][j], cache);
        int left = helper(matrix, i, j - 1, matrix[i][j], cache);
        int right = helper(matrix, i, j + 1, matrix[i][j], cache);
        
        return Math.max(Math.max(up, down), Math.max(left, right)) + 1;
    }
}
時間複雜度是O(2^(m+n))

Complexity Analysis

  • Time complexity :
    O(2^{m+n})

    The search is repeated for each valid increasing path. In the worst case we can have
    O(2^{m+n}) calls. For example:

1 23 . . . n

2 3. . .   n+1

3 . . .     n+2

.           .

.           .

.           .

m m+1. . . n+m-1

  • Space complexity :
    O(mn). For each DFS we need O(h) space used by the system stack, whereh is the maximum depth of the recursion. In the worst case,  O(h) = O(mn)
怎麼看出來O(2^{m+n})的呢?這裡引用了leetcode解題分析的極端例子,上面那個matrix,遞增只有向右或者向下2個方向,左上角的1看做binary tree的root, 那麼這個tree的depth就是m+n, 複雜度就是 2^(m + n) + 2^(m + n - 1) + ... + 2^2 + 2 ^ 1.  可以看成是 m * n * 2^(m + n). m*n忽略,也就是O(2^{m+n})了,指數級,exponential.


如何優化呢? 從[0][0]出發, 到[0][1]會做一遍從[0][1]出發的DFS,然後for迴圈到[0][1]後,有會做一次DFS,顯然重複計算了, 所以可以用memorization來優化複雜度, 用一個二維陣列int[][] cache來記錄從當前位置DFS得到的longest increasing path length,存進去, 那後面再有需要到這個點遍歷就可以直接取出值來用, 沒有重複訪問,複雜度是O(m*n);
程式碼如下
public class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0)
            return 0;
        int res = Integer.MIN_VALUE;
        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 max = helper(matrix, i, j, Integer.MIN_VALUE, cache);
                res = Math.max(res, max);
            }
        }
        
        return res;
    }
    
    private int helper(int[][] matrix, int i, int j, int val, int[][]cache){
        if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length)
            return 0;
        if(matrix[i][j] <= val){
            return 0;
        }
        if(cache[i][j] != 0){
            return cache[i][j] + 1;
        }else{
            int up = helper(matrix, i - 1, j, matrix[i][j], cache);
            int down = helper(matrix, i + 1, j, matrix[i][j], cache);
            int left = helper(matrix, i, j - 1, matrix[i][j], cache);
            int right = helper(matrix, i, j + 1, matrix[i][j], cache);
            
            int max =  Math.max(Math.max(up, down), Math.max(left, right));
            cache[i][j] = max;
            return max + 1;
        }
    }
}