[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).ide

Example 1:spa

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

Return 4
The longest increasing path is [1, 2, 6, 9].code

Example 2:blog

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.遞歸

 

解法:it

  這道題給咱們一個二維數組,讓咱們求矩陣中最長的遞增路徑,規定咱們只能上下左右行走,不能走斜線或者是超過了邊界。那麼這道題的解法要用遞歸和DP來解,用DP的緣由是爲了提升效率,避免重複運算。咱們須要維護一個二維動態數組dp,其中dp[i][j]表示數組中以(i,j)爲起點的最長遞增路徑的長度,初始將dp數組都賦爲0,當咱們用遞歸調用時,遇到某個位置(x, y), 若是dp[x][y]不爲0的話,咱們直接返回dp[x][y]便可,不須要重複計算。咱們須要以數組中每一個位置都爲起點調用遞歸來作,比較找出最大值。在以一個位置爲起點用深度優先搜索DFS時,對其四個相鄰位置進行判斷,若是相鄰位置的值大於上一個位置,則對相鄰位置繼續調用遞歸,並更新一個最大值,搜素完成後返回便可,參見代碼以下:io

public class Solution {
    public int longestIncreasingPath(int[][] matrix) {
        if (matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        int m = matrix.length, n = matrix[0].length;
        int res = 0;
        int[][] dp = new int[m][n];
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res = Math.max(res, findLongestPath(matrix, dp, i, j));
            }
        }
        return res;
    }
    
    public int findLongestPath(int[][] matrix, int[][] dp, int i, int j) {
        dp[i][j] = 1;
        int[][] next = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        for (int k = 0; k < next.length; k++) {
            int ni = i + next[k][0];
            int nj = j + next[k][1];
            if (ni >= 0 && ni < dp.length && nj >= 0 && nj < dp[0].length && matrix[ni][nj] > matrix[i][j]) {
                if (dp[ni][nj] != 0) {
                    dp[i][j] = Math.max(dp[i][j], dp[ni][nj] + 1);
                } else {
                    dp[i][j] = Math.max(dp[i][j], findLongestPath(matrix, dp, ni, nj) + 1);
                }
            }
        }
        return dp[i][j];
    }
}
相關文章
相關標籤/搜索