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
因为最长的路径其实是可以从任意一点开始的,所以可以开一个vector<vector<int>> dp来存储从这个矩阵中每一个点开始作为路径起始点的最长路径的长度。这样做之后,只需要遍历这个数组,就能知道题目需要求解的最长路径是多长。
求dp中元素的值:对于dp中的每一个元素dp[i][j],因为题目规定了只能上下左右地移动,移动的条件当然是要移动到的目标位置的值比[i][j]位置的值要大,不然就不满足递增的要求。所以dp[i][j]应该移动到它可以移动的并且具有最长递增路径的那个点上,也就是dp[i][j]=max(max(left, right), max(up, down))。
要求存储dp的值,不然的话就容易超时。
代码:
class Solution {
public:
int dfs(vector<vector<int>>& matrix, vector<vector<int>>& dp, int i, int j, int row, int col){
if(dp[i][j]>0) return dp[i][j];
int r=1, l=1, u=1, d=1;
//left
if(j>0 && matrix[i][j-1]>matrix[i][j]){
l=1+dfs(matrix, dp, i, j-1, row, col);
}
//right
if(j<col-1 && matrix[i][j+1]>matrix[i][j]){
r=1+dfs(matrix, dp, i, j+1, row, col);
}
//up
if(i>0 && matrix[i-1][j]>matrix[i][j]){
u=1+dfs(matrix, dp, i-1, j, row, col);
}
//down
if(i<row-1 && matrix[i+1][j]>matrix[i][j]){
d=1+dfs(matrix, dp, i+1, j, row, col);
}
dp[i][j]=max(max(r, l), max(u, d));
return dp[i][j];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
int row=matrix.size();
if(row==0) return 0;
int col=matrix[0].size();
vector<vector<int>> dp(row, vector<int> (col, 0));
int mmax=0;
int temp=0;
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
temp=dfs(matrix, dp, i, j, row, col);
if(temp>mmax) mmax=temp;
}
}
return mmax;
}
};