题目:
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[i][j]表示以(i,j)结尾的最长下降序列的长度。
虽然标着hard,其实是很简单的。
但是,这个题有个巨大的坑,就是输入的可能是一个空矩阵,输出应该是0。这个我没有特判。
class Solution {
public:
int n, m;
int dx[4];
int dy[4];
int longestIncreasingPath(vector< vector<int> >& matrix) {
dx[0] = -1; dx[1] = 0; dx[2] = 0; dx[3] = 1;
dy[0] = 0; dy[1] = 1; dy[2] = -1; dy[3] = 0;
int ans = 0;
n = matrix.size();
if (n != 0) m = matrix[0].size();
else return 0;
vector< vector<int> > dp(n,vector<int>(m, -1));
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
dfs(matrix, dp, i, j);
ans = max(ans, dp[i][j]);
}
return ans;
}
int dfs(vector< vector<int> >& matrix, vector< vector<int> >& dp, int x, int y) {
if (dp[x][y] != -1) return dp[x][y];
dp[x][y] = 1;
int nx, ny;
for (int i = 0; i < 4; i++) {
nx = x + dx[i];
ny = y + dy[i];
if (nx >= 0 && nx < n && ny >= 0 && ny < m)
if (matrix[nx][ny] < matrix[x][y])
dp[x][y] = max(dp[x][y], dfs(matrix, dp, nx, ny) + 1);
}
return dp[x][y];
}
};