给定一个整数矩阵,找出最长递增路径的长度。
对于每个单元格,你可以往上,下,左,右四个方向移动。 你不能在对角线方向上移动或移动到边界外(即不允许环绕)。
示例 1:
输入: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
输出: 4
解释: 最长递增路径为 [1, 2, 6, 9]。```
示例 2:
输入: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
输出: 4
解释: 最长递增路径是 [3, 4, 5, 6]。注意不允许在对角线方向上移动。
解法
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int res=0;//用来存放结果
//用两个数组代表上下左右移动
const int dx[4] = {1, 0, 0, -1};
const int dy[4] = {0, 1, -1, 0};
//dp[i][j]代表移动到matrix[i][j]的最长增长路径
//第一步骤,先计算出度
int row=matrix.size();
if(row<=0) return 0;
int col=matrix[0].size();
if(col<=0||row<=0) return 0;
vector<vector<int>> degree(row,vector<int>(col,0));
//计算出度
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
for(int k=0;k<4;k++)
{
int newrow=i+dx[k];
int newcol=j+dy[k];
if(newrow>=0&&newrow<row&&newcol>=0&&newcol<col&&matrix[newrow][newcol]>matrix[i][j])
degree[i][j]++;
}
}
}
//用dps
queue<pair<int,int>> q;
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(degree[i][j]==0)
q.push(pair(i,j));
}
}
while(!q.empty())
{
res++;
int size=q.size();
for(int l=0;l<size;l++)
{
auto cell=q.front(); q.pop();
int i=cell.first;
int j=cell.second;
for(int k=0;k<4;k++)
{
int newrow=i+dx[k];
int newcol=j+dy[k];
if(newrow>=0&&newrow<row&&newcol>=0&&newcol<col&&matrix[newrow][newcol]<matrix[i][j])
{
degree[newrow][newcol]--;
if(degree[newrow][newcol]==0)
q.push(pair(newrow,newcol));
}
}
}
}
return res;
}
};
871

被折叠的 条评论
为什么被折叠?



