首先给出有向无环图DFS的伪代码:
Leetcode 329. Longest Increasing Path in a Matrix
代码如下:
class Solution {
public:
int longestIncreasingPath(vector<vector<int> >& matrix) {
int row = matrix.size();
if (row == 0) return 0;
int col = matrix[0].size();
vector<int> temp(col,0);
vector<vector<int> > cache(row,temp);
int max = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int tmp = explore(i,j,cache,matrix);
if (tmp > max) max = tmp;
}
}
return max;
}
bool valid(int r, int c, vector<vector<int> >& matrix) {
return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size();
}
int explore(int r, int c, vector<vector<int> >& cache, vector<vector<int> >& matrix) {
if (cache[r][c] != 0) return cache[r][c];
int max = 0;
if (valid(r-1,c,matrix) && matrix[r-1][c] > matrix[r][c]) {
int up = explore(r-1,c,cache,matrix);
max = up;
}
if (valid(r+1,c,matrix) && matrix[r+1][c] > matrix[r][c]) {
int down = explore(r+1,c,cache, matrix);
if (down > max) max = down;
}
if (valid(r,c-1,matrix) && matrix[r][c-1] > matrix[r][c]) {
int left = explore(r,c-1,cache,matrix);
if (left > max) max = left;
}
if (valid(r,c+1,matrix) && matrix[r][c+1] > matrix[r][c]) {
int right = explore(r,c+1,cache,matrix);
if (right > max) max = right;
}
cache[r][c] = 1 + max;
return 1 + max;
}
};