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.

DP + DFS

复杂度
O(MN),O(N)

思路
为了避免搜索已经搜索的点。所以考虑用一个dp数组,记录到每一个点能产生的最长序列的长度。考虑用dfs进行搜索,对于每一个点来说,考虑先找到最小的那个点针对每一条路径的。然后对于每一点再递增回去,依次累积找到增加的值。

代码

public int longestIncreasingPath(int[][] matrix) {
    if(matrix.length == 0) return 0; 
    int row = matrix.length, col = matrix[0].length;
    int[][] dp = new int[row][col];
    //dp = {0};
    int val = 0;
    for(int i = 0; i < row; i ++) {
        for(int j = 0; j < col; j ++) {
            if(helper(matrix, i, j, dp) > val) {
                val = helper(matrix, i, j, dp);
            }
        }
    }
    return val;
}

public int helper(int[][] matrix, int i, int j, int[][] dp) {
    //this is the point;
    if(dp[i][j] != 0) return dp[i][j];
    int val = 0;
    if(i + 1 < matrix.length && matrix[i + 1][j] < matrix[i][j]) {
        val = Math.max(val, helper(matrix, i + 1, j, dp));
    }
    if(i - 1 >= 0 && matrix[i - 1][j] < matrix[i][j]) {
        val = Math.max(val, helper(matrix, i - 1, j, dp));
    }
    if(j + 1 < matrix[0].length && matrix[i][j + 1] < matrix[i][j]) {
        val = Math.max(val, helper(matrix, i, j + 1, dp));
    }
    if(j - 1 >= 0 && matrix[i][j - 1] < matrix[i][j]) {
        val = Math.max(val, helper(matrix, i, j - 1, dp));
    }
    dp[i][j] = val + 1;
    return dp[i][j];
}


hellolittleJ17
10 声望11 粉丝