题解
Hard
方法一:DFS + Memoization
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty()) return 0;
m = matrix.size(), n = matrix[0].size();
vector<vector<int>> cache(m, vector<int>(n, 0));
int res = 1;
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
res = max(res, dfs(matrix, i, j, cache));
}
}
return res;
}
int dfs(vector<vector<int>>& matrix, int x, int y, vector<vector<int>>& cache) {
if(cache[x][y] != 0) return cache[x][y];
cache[x][y] = 1;
for(int i = 0; i < 4; i++) {
int new_x = x + dirs[i][0];
int new_y = y + dirs[i][1];
if(new_x >= 0 && new_x < m && new_y >= 0 && new_y < n
&& matrix[new_x][new_y] > matrix[x][y]) {
cache[x][y] = max(cache[x][y], dfs(matrix, new_x, new_y, cache) + 1);
}
}
return cache[x][y];
}
private:
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int m, n;
};