【题目】
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]
.
建图,如果a < b,则a到b有一条有向边。然后拓扑排序。
然后从拓扑排序排在后面的节点开始用动态规划算从这个节点开始最大的路径长度。然后再找最大的。。。。。。
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
int r = matrix.size();
if (r == 0) return 0;
int c = matrix[0].size();
this->row = r;
this->col = c;
vector<pair<int, int>> top_order(row * col);
vector<vector<int>> path_len(row, vector<int>(col, 0));
top_sort(matrix, top_order);
int result = 0;
for (int i = row * col - 1; i >= 0; i--) {
int m = 1;
for (int j = 0; j < 4; j++) {
int x = top_order[i].first + dx[j], y = top_order[i].second + dy[j];
if (x < 0 || x >= row || y < 0 || y >= col) continue;
if (matrix[x][y] > matrix[top_order[i].first][top_order[i].second]) {
if (1 + path_len[x][y] > m) {
m = 1 + path_len[x][y];
}
}
}
path_len[top_order[i].first][top_order[i].second] = m;
if (result < m) result = m;
}
return result;
}
void top_sort(vector<vector<int>>& matrix, vector<pair<int, int>>& top_order) {
int n = row * col - 1;
vector<vector<bool>> visited(row, vector<bool>(col, false));
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (!visited[i][j]) {
visited[i][j] = true;
dfs(matrix, top_order, i, j, n, visited);
}
}
}
}
void dfs(vector<vector<int>>& matrix, vector<pair<int, int>>& top_order, int sx, int sy, int& n, vector<vector<bool>>& visited) {
for (int i = 0; i < 4; i++) {
int x = sx + dx[i], y = sy + dy[i];
if (x < 0 || x >= row || y < 0 || y >= col || visited[x][y] || matrix[x][y] <= matrix[sx][sy]) continue;
visited[x][y] = true;
dfs(matrix, top_order, x, y, n, visited);
}
top_order[n] = make_pair(sx, sy);
n--;
}
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1, 0, -1, 0 };
int row;
int col;
};