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).
method 1 DFS+dp
直接使用DFS会超时,所以将想到使用dp,并且递增序列已经严格限制了点的顺序,这样就防止重复计算dp数组,只有该点位置的值小于(大于)邻近的值,才能在对应的dp上加1,最后四个方向计算完毕后取最大的。
int maxLength = 1;
int helper(vector<vector<int>>& matrix, int i, int j, vector<vector<int>>& dp){
if (dp[i][j] != 0) return dp[i][j];
int dirc[] = { 0, 1, 0, -1, 0 };
int m = matrix.size(), n = matrix[0].size();
int curLength = 1;
for (int k = 0; k < 4; k++)
{
int x = i + dirc[k], y = j + dirc[k + 1];
if (x >= 0 && y >= 0 && x < m && y < n && matrix[i][j] < matrix[x][y]){
int dist = 1 + helper(matrix, x, y, dp);
curLength = max(dist, curLength);
}
}
dp[i][j] = curLength;
return curLength;
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.size() == 0) return 0;
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> dp;
for (int i = 0; i < m; i++)
{
vector<int> vec;
for (int j = 0; j < n; j++)
{
vec.push_back(0);
}
dp.push_back(vec);
}
for (int i = 0; i < matrix.size(); i++)
{
for (int j = 0; j < matrix[i].size(); j++)
{
maxLength = max(maxLength, helper(matrix, i, j, dp));
}
}
return maxLength;
}
method 2 topological sort
本题可以抽象为一个DAG,method 1表现得正是DAG上的动态规划。
本题所求的可以看作DAG上的一个最长递增序列,正因为严格递增的关系,所以可以使用拓扑排序。使用拓扑排序,那么就要计算各点的入度,这里规定点(x,y)附近值比(x,y)更大的点的个数为其入度
使用BFS进行拓扑排序,使用一个length记录拓扑排序后序列的长度。当入度为0时,将新的点压入队列
public int longestIncreasingPath(int[][] matrix) {
// Corner cases
if (matrix.length == 0) {
return 0;
}
int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int rows = matrix.length, cols = matrix[0].length;
// indegree[i][j] indicates thee number of adjacent cells bigger than matrix[i][j]
int[][] indegree = new int[rows][cols];
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
for (int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {
if (matrix[nx][ny] > matrix[x][y]) {
indegree[x][y]++;
}
}
}
}
}
// Add each cell with indegree zero to the queue
Queue<int[]> queue = new LinkedList<>();
for (int x = 0; x < rows; x++) {
for (int y = 0; y < cols; y++) {
if (indegree[x][y] == 0) {
queue.offer(new int[]{x, y});
}
}
}
int length = 0; // The longest path so far
// BFS implements the Topological Sort
while(!queue.isEmpty()) {
int sz = queue.size();
for (int i = 0; i < sz; i++) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for (int[] dir: dirs) {
int nx = x + dir[0];
int ny = y + dir[1];
if (nx >= 0 && nx < rows && ny >= 0 && ny < cols) {
if (matrix[nx][ny] < matrix[x][y]
&& --indegree[nx][ny] == 0) {
queue.offer(new int[]{nx, ny});
}
}
}
}
length++;
}
return length;
}
summary
- 建立将问题抽象为DAG的抽象思维
- 当所求的解具有严格的顺序,考虑使用BFS求拓扑排序