题目描述:
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:
nums = [ [9,9,4], [6,6,8], [2,1,1] ]
Return 4
The longest increasing path is [1, 2, 6, 9]
.
Example 2:
nums = [ [3,4,5], [3,2,6], [2,2,1] ]
Return 4
The longest increasing path is [3, 4, 5, 6]
. Moving diagonally is not allowed.
对于矩阵中的每一个数字,用深度优先遍历寻找最比当前数字大的数字,对于已经走过的数字,将其置位为INT_MIN,下次经过这个数字可以直接不用考虑。如果走到某个位置,其上下左右的数字都比当前数字小,那么说明已经无路可走,那么就得进行回溯,回溯的过程中必须将之前置位为INT_MIN的数字恢复为初始数字。
代码如下:
class Solution {
private:
int curLen;
int maxLen;
int row;
int col;
public:
void Move(vector<vector<int> >& matrix, int x, int y)
{
int cur = matrix[x][y];
matrix[x][y] = INT_MIN;
curLen++;
if (curLen > maxLen)
{
if (curLen == 8)
{
curLen = curLen;
}
maxLen = curLen;
}
if (y + 1 < col && matrix[x][y+1] > cur)
{
Move(matrix, x, y+1);
}
if (y - 1 >= 0 && matrix[x][y-1] > cur)
{
Move(matrix, x, y-1);
}
if (x + 1 < row && matrix[x+1][y] > cur)
{
Move(matrix, x+1, y);
}
if (x - 1 >= 0 && matrix[x-1][y] > cur)
{
Move(matrix, x-1, y);
}
matrix[x][y] = cur;
curLen--;
}
int longestIncreasingPath(vector<vector<int> >& matrix) {
if (matrix.empty()||matrix[0].empty()) return 0;
row = matrix.size();
col = matrix[0].size();
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
curLen = 0;
Move(matrix, i, j);
}
}
return maxLen;
}
};