# LeetCode. 矩阵中的最长递增路径

[
[9,9,4],
[6,6,8],
[2,1,1]
]


class Solution {
public:
int dx[5] = {-1, 0, 1, 0};
int dy[5] = {0, 1, 0, -1};

int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty()) return 0;
int max1 = 0;
vector<vector<bool>> visited(matrix.size()+1, vector<bool>(matrix[0].size()+1, false));
vector<vector<int>> len(matrix.size()+1, vector<int>(matrix[0].size()+1, 0));
for(int i = 0; i < matrix.size(); i++) {
for(int j = 0; j < matrix[0].size(); j++) {
max1 = max(max1, find(matrix, visited, len, i, j));
}
}
return max1;
}

int find(vector<vector<int>> matrix, vector<vector<bool>> visited, vector<vector<int>> len, int x, int y) {
if(visited[x][y]) {
return len[x][y];
}
len[x][y] = 1;
for(int i = 0; i < 4; i++) {
int _x = dx[i] + x;
int _y = dy[i] + y;
if(_x >= 0 && _x < matrix.size() && _y >= 0 && _y < matrix.size() && matrix[_x][_y] < matrix[x][y]) {
len[x][y] = max(len[x][y], find(matrix, visited, len, _x, _y) + 1);
}
}
visited[x][y] = true;
return len[x][y];
}
};

posted @ 2019-10-15 20:20  Howardwang  阅读(404)  评论(0编辑  收藏