题目:
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:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9]
.
Example 2:
Input: nums =
[
[3,4,5],
[3,2,6],
[2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
代码:
class Solution {
public:
int length = INT_MIN;
vector<vector<int>> directions = { {0,1},{0,-1},{1,0},{-1,0} };
int helper(vector<vector<int>>& records,vector<vector<int>>& matrix, int x, int y, int l) {
if (records[x][y] != 0)return records[x][y];
//length = max(length, l);
for (int i = 0; i < directions.size(); i++) {
int hx = x + directions[i][0];
int hy = y + directions[i][1];
if (hx<0 || hy<0 || hx>=matrix.size() || hy>=matrix[0].size())continue;
if (matrix[hx][hy] <= matrix[x][y])continue;
if (records[hx][hy] != 0) {
records[x][y] = max(records[x][y], records[hx][hy] + 1);
}
else {
int temp = matrix[x][y];
matrix[x][y] = 0;
records[x][y]=max(records[x][y],helper(records, matrix, hx, hy, l + 1)+1);
matrix[x][y] = temp;
}
}
return records[x][y];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
int h = matrix.size();
if (h == 0)return 0;
int w = matrix[0].size();
if (w == 0)return 0;
vector<vector<int>> records(h, vector<int>(w, 0));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
length=max(length,helper(records,matrix, i, j, 1));
}
}
return length+1;
}
};
思路:
记忆化搜索+DFS