[LeetCode] Longest Increasing Path in a Matrix 矩陣中的最長遞增路徑

 

Given an integer matrix, find the length of the longest increasing path.html

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).java

Example 1:數組

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

 

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

Example 2:post

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來解,用DP的緣由是爲了提升效率,避免重複運算。咱們須要維護一個二維動態數組dp,其中dp[i][j]表示數組中以(i,j)爲起點的最長遞增路徑的長度,初始將dp數組都賦爲0,當咱們用遞歸調用時,遇到某個位置(x, y), 若是dp[x][y]不爲0的話,咱們直接返回dp[x][y]便可,不須要重複計算。咱們須要以數組中每一個位置都爲起點調用遞歸來作,比較找出最大值。在以一個位置爲起點用DFS搜索時,對其四個相鄰位置進行判斷,若是相鄰位置的值大於上一個位置,則對相鄰位置繼續調用遞歸,並更新一個最大值,搜素完成後返回便可,參見代碼以下:url

 

解法一:spa

class Solution {
public:
    vector<vector<int>> dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int res = 1, m = matrix.size(), n = matrix[0].size();
        vector<vector<int>> dp(m, vector<int>(n, 0));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                res = max(res, dfs(matrix, dp, i, j));
            }
        }
        return res;
    }
    int dfs(vector<vector<int>> &matrix, vector<vector<int>> &dp, int i, int j) {
        if (dp[i][j]) return dp[i][j];
        int mx = 1, m = matrix.size(), n = matrix[0].size();
        for (auto a : dirs) {
            int x = i + a[0], y = j + a[1];
            if (x < 0 || x >= m || y < 0 |a| y >= n || matrix[x][y] <= matrix[i][j]) continue;
            int len = 1 + dfs(matrix, dp, x, y);
            mx = max(mx, len);
        }
        dp[i][j] = mx;
        return mx;
    }
};

 

下面再來看一種BFS的解法,須要用queue來輔助遍歷,咱們仍是須要dp數組來減小重複運算。遍歷數組中的每一個數字,跟上面的解法同樣,把每一個遍歷到的點都看成BFS遍歷的起始點,須要優化的是,若是當前點的dp值大於0了,說明當前點已經計算過了,咱們直接跳過。不然就新建一個queue,而後把當前點的座標加進去,再用一個變量cnt,初始化爲1,表示當前點爲起點的遞增加度,而後進入while循環,而後cnt自增1,這裏先自增1沒有關係,由於只有當週圍有合法的點時候纔會用cnt來更新。因爲當前結點周圍四個相鄰點距當前點距離都同樣,因此採用相似二叉樹層序遍歷的方式,先出當前queue的長度,而後遍歷跟長度相同的次數,取出queue中的首元素,對周圍四個點進行遍歷,計算出相鄰點的座標後,要進行合法性檢查,橫縱座標不能越界,且相鄰點的值要大於當前點的值,而且相鄰點點dp值要小於cnt,纔有更新的必要。用cnt來更新dp[x][y],並用cnt來更新結果res,而後把相鄰點排入queue中繼續循環便可,參見代碼以下:code

 

解法二:htm

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int m = matrix.size(), n = matrix[0].size(), res = 1;
        vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
        vector<vector<int>> dp(m, vector<int>(n, 0));
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j ) {
                if (dp[i][j] > 0) continue;
                queue<pair<int, int>> q{{{i, j}}};
                int cnt = 1;
                while (!q.empty()) {
                    ++cnt;
                    int len = q.size();
                    for (int k = 0; k < len; ++k) {
                        auto t = q.front(); q.pop();
                        for (auto dir : dirs) {
                            int x = t.first + dir[0], y = t.second + dir[1];
                            if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[t.first][t.second] || cnt <= dp[x][y]) continue;
                            dp[x][y] = cnt;
                            res = max(res, cnt);
                            q.push({x, y});
                        }
                    }
                }
            }
        }
        return res;
    }
};

 

參考資料:

https://discuss.leetcode.com/topic/35052/iterative-java-bfs-solution

 

LeetCode All in One 題目講解彙總(持續更新中...)

相關文章
相關標籤/搜索