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.
分析
这一题是一道特别典型的深搜的题目,同时加上剪枝的应用。寻找一个最长的路径,很自然的想到深搜,遍历二维数组的每一个点,在搜索的时时候遍历[i,j]周围的四个点,如果值大于matrix[i][j],执行dfs,如果<=,则跳过。
如果这么暴力深搜的话,会发新TimeLimitError。
那么我们怎么优化?一个点在于,如果[i][j]周围有小于matirx[i][j]的点,那么从[i][j]出发的路径一定不是最长路径,所以需要[i][j]应该直接跳过。
还有一点,如果我们可以在搜索过程中的已经记录的路径长度,使用二维数组path记录到达该点的最长路径。例如path[i][j]记录曾经的搜索过程中到达[i][j]点的最长路径,那么在之后的搜索时候如果如果同样的搜索了该点,如果当前的路径小于path[i][j]的值,那么就没有必要继续搜索下去,因为前面一定已经有更长的长度了。
Code
class Solution {
public:
int row;
int col;
int longestIncreasingPath(vector<vector<int>>& matrix) {
row = matrix.size();
if (row == 0)
return 0;
col = matrix[0].size();
for (int i = 0; i < row; i ++)
{
matrix[i].insert(matrix[i].begin(), INT_MIN);
matrix[i].push_back(INT_MIN);
}
matrix.insert(matrix.begin(), vector<int>(col+2, INT_MIN));
matrix.push_back(vector<int>(col+2, INT_MIN));
vector<vector<int>> path(row+2, vector<int>(col+2, 0));
int res = 0;
for (int i = 1; i <= row; i ++)
{
for (int j = 1; j <= col; j ++)
{
if ((i > 1 && matrix[i-1][j] < matrix[i][j]) ||
(i < row && matrix[i+1][j] < matrix[i][j]) ||
(j > 1 && matrix[i][j-1] < matrix[i][j]) ||
(j < col && matrix[i][j+1] < matrix[i][j]))
{
continue;
}
getPath(matrix, i, j, path, 1);
}
}
for (int i = 1; i <= row; i ++)
for (int j = 1; j <= col; j ++)
res = max(res, path[i][j]);
return res;
}
void getPath(vector<vector<int>>& matrix, int x, int y, vector<vector<int>>& path, int length)
{
if (length <= path[x][y])
return;
path[x][y] = length;
if (matrix[x-1][y] > matrix[x][y])
{
getPath(matrix, x-1, y, path, length +1);
}
if (matrix[x+1][y] > matrix[x][y])
{
getPath(matrix, x+1, y, path, length + 1);
}
if (matrix[x][y-1] > matrix[x][y])
{
getPath(matrix, x, y-1, path, length +1);
}
if (matrix[x][y+1] > matrix[x][y])
{
getPath(matrix, x, y+1, path, length +1);
}
return;
}
};
运行效率
Runtime: 84 ms, faster than 35.75% of C++ online submissions for Longest Increasing Path in a Matrix.
Memory Usage: 14.8 MB, less than 48.57% of C++ online submissions for Longest Increasing Path in a Matrix.