# C++ | Leetcode C++题解之第329题矩阵中的最长递增路径

371 篇文章 2 订阅

class Solution {
public:
static constexpr int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int rows, columns;

int longestIncreasingPath(vector< vector<int> > &matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return 0;
}
rows = matrix.size();
columns = matrix[0].size();
auto outdegrees = vector< vector<int> > (rows, vector <int> (columns));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
for (int k = 0; k < 4; ++k) {
int newRow = i + dirs[k][0], newColumn = j + dirs[k][1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] > matrix[i][j]) {
++outdegrees[i][j];
}
}
}
}
queue < pair<int, int> > q;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < columns; ++j) {
if (outdegrees[i][j] == 0) {
q.push({i, j});
}
}
}
int ans = 0;
while (!q.empty()) {
++ans;
int size = q.size();
for (int i = 0; i < size; ++i) {
auto cell = q.front(); q.pop();
int row = cell.first, column = cell.second;
for (int k = 0; k < 4; ++k) {
int newRow = row + dirs[k][0], newColumn = column + dirs[k][1];
if (newRow >= 0 && newRow < rows && newColumn >= 0 && newColumn < columns && matrix[newRow][newColumn] < matrix[row][column]) {
--outdegrees[newRow][newColumn];
if (outdegrees[newRow][newColumn] == 0) {
q.push({newRow, newColumn});
}
}
}
}
}
return ans;
}
};
• 4
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
09-16
09-16
09-16
09-16

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。