1. 程式人生 > >[LeetCode] Longest Increasing Path in a Matrix 矩陣中的最長遞增路徑

[LeetCode] 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來解,用DP的原因是為了提高效率,避免重複運算。我們需要維護一個二維動態陣列dp,其中dp[i][j]表示陣列中以(i,j)為起點的最長遞增路徑的長度,初始將dp陣列都賦為0,當我們用遞迴呼叫時,遇到某個位置(x, y), 如果dp[x][y]不為0的話,我們直接返回dp[x][y]即可,不需要重複計算。我們需要以陣列中每個位置都為起點呼叫遞迴來做,比較找出最大值。在以一個位置為起點用DFS搜尋時,對其四個相鄰位置進行判斷,如果相鄰位置的值大於上一個位置,則對相鄰位置繼續呼叫遞迴,並更新一個最大值,搜素完成後返回即可,參見程式碼如下:

解法一:

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中繼續迴圈即可,參見程式碼如下:

解法二:

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;
    }
};

參考資料: