题目描述
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 dir[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.empty()) return 0;
n = matrix.size();
m = matrix[0].size();
dp = vector<vector<int>> (n, vector<int>(m));
int ans = 1;
for (int i=0; i<n; ++i) {
for (int j=0; j<m; ++j) {
if (dp[i][j]) ans = max(ans, dp[i][j]);
ans = max(ans, dfs(i, j, 1, matrix));
}
}
return ans;
}
int dfs(int x, int y, int cur, vector<vector<int>>& matrix) {
if (dp[x][y]) return dp[x][y];
int ans = 0;
for (int i=0; i<4; ++i) {
int nxtx = x + dir[i][0];
int nxty = y + dir[i][1];
if (nxtx < 0 || nxty < 0 || nxtx >=n || nxty >= m) continue;
if (matrix[nxtx][nxty] <= matrix[x][y]) continue;
ans = max(ans, dfs(nxtx, nxty, 1, matrix));
}
return dp[x][y] = cur+ans;
}
private:
vector<vector<int>> dp;
int n, m;
};
今天做的题居然都没看题解…hhhh