【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].

Example 2:

Input: nums = 
[
  [3,4,5],
  [3,2,6],
  [2,2,1]
] 
Output: 4 
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

代碼

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int n = matrix.size();
        int m = matrix[0].size();
        vector<vector<int>> res(n, vector<int>(m, 0));
        int ans = 0;
        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                if (res[i][j] == 0) {
                    ans = max(ans, bfs(i, j, res, matrix));
                } 
            }
        }
        return ans;
    }
    
    vector<int> dirs {1, 0, -1, 0, 1};
    
    int bfs(int x, int y, vector<vector<int>>& res, vector<vector<int>>& matrix) {
        if (res[x][y] != 0) return res[x][y];
        int ans = 0;
        for (int i=0; i<4; ++i) {
            int nx = x + dirs[i];
            int ny = y + dirs[i+1];
            if (nx < 0 || nx >= res.size() || ny < 0 || ny >= res[0].size()) {
                continue;
            }
            if (matrix[nx][ny] >= matrix[x][y]) continue;
            ans = max(ans, bfs(nx, ny, res, matrix));
        }
        res[x][y] = ans+1;
        return res[x][y];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章