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:

Input: nums = 
[
  [9,9,4],
  [6,6,8],
  [2,1,1]
] 

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

思路:
直接用DFS遍历所有路径会TLE
所以用dp数组储存之前DFS的结果,矩阵中一个点(x, y)的最长递增路径相当于它上下左右的四个相邻点的路径长+1
走到一个(x, y)点时,首先把当前路径长设为1,然后根据相邻的4个点进行更新,而且,因为是递增path,所以要判断原矩阵中相邻点处的值>当前点处的值时才算递增,<=当前点处的值时路径长直接就是1。还要判断是否超出边界。

dfs计算本身会遍历到所有的dp元素,主函数中遍历matrix是取dp中所有结果的最大值,也就是最长的递增路径长度。

class Solution {
    private int rows = 0;
    private int cols = 0;
    private int[][] dp;
    public int longestIncreasingPath(int[][] matrix) {
        if(matrix == null || matrix.length == 0) {
            return 0;
        }
        
        rows = matrix.length;
        cols = matrix[0].length;
        dp = new int[rows][cols];
        //for(int i = 0; i < rows; i++) {
        //    Arrays.fill(dp[i], -1);
        //}
              
        int result = 0;
        
        for(int i = 0; i < rows; i++) {
            for(int j = 0; j < cols; j++) {
                result = Math.max(result, dfs(matrix, i, j));
            }
        }
        
        return result;
    }
    
    public int dfs(int[][] matrix, int row, int col) {
        if(dp[row][col] != 0) {
            return dp[row][col];
        }
        
        int[] offset = new int[]{-1, 0, 1, 0, -1};
        int nrow = 0;   //neighbor x
        int ncol = 0;   //neighbor y
        
         
        dp[row][col] = 1;
        for(int i = 0; i < 4; i++) {
            ncol = col + offset[i];
            nrow = row + offset[i + 1];
                    
            if(ncol < 0 || nrow < 0 || ncol >= cols || nrow >= rows ||
                     matrix[nrow][ncol] <= matrix[row][col]) {
                continue;
            }
                    
            dp[row][col] = Math.max(dp[row][col], 1 + dfs(matrix, nrow, ncol));
        } 
        
        return dp[row][col];
    }
}

你可能感兴趣的:(leetcode)