class Solution {
public:
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0)
return 0;
int xmax = matrix.size();
int ymax = matrix[0].size();
int ** tmp = new int*[xmax];
for (int i = 0; i < xmax; i++)
{
tmp[i] = new int[ymax];
for (int j = 0; j < ymax; j++)
{
tmp[i][j] = 0;
}
}
int maxlen = 0;
for (int i = 0; i < xmax; i++)
{
for (int j = 0; j < ymax; j++)
{
maxlen = max(maxlen, dp(matrix, i, j, tmp, xmax, ymax));
}
}
return maxlen;
}
int dp(vector<vector<int>> &matrix, int i, int j, int ** tmp, int xmax, int ymax)
{
if (tmp[i][j] != 0)
{
return tmp[i][j];
}
int xdir[4] = { 1, 0, -1, 0 };
int ydir[4] = { 0, 1, 0, -1 };
tmp[i][j] = 1;
for (int k = 0; k < 4; k++)
{
int x = i + xdir[k];
int y = j + ydir[k];
if (x >= 0 && x < xmax && y >= 0 && y < ymax && matrix[x][y]>matrix[i][j])
{
int maxlen = max(dp(matrix, x, y, tmp, xmax, ymax) + 1, tmp[i][j]);
tmp[i][j] = maxlen;
}
}
return tmp[i][j];
}
};
public:
int longestIncreasingPath(vector<vector<int>> &matrix)
{
if (matrix.size() == 0)
return 0;
int xmax = matrix.size();
int ymax = matrix[0].size();
int ** tmp = new int*[xmax];
for (int i = 0; i < xmax; i++)
{
tmp[i] = new int[ymax];
for (int j = 0; j < ymax; j++)
{
tmp[i][j] = 0;
}
}
int maxlen = 0;
for (int i = 0; i < xmax; i++)
{
for (int j = 0; j < ymax; j++)
{
maxlen = max(maxlen, dp(matrix, i, j, tmp, xmax, ymax));
}
}
return maxlen;
}
int dp(vector<vector<int>> &matrix, int i, int j, int ** tmp, int xmax, int ymax)
{
if (tmp[i][j] != 0)
{
return tmp[i][j];
}
int xdir[4] = { 1, 0, -1, 0 };
int ydir[4] = { 0, 1, 0, -1 };
tmp[i][j] = 1;
for (int k = 0; k < 4; k++)
{
int x = i + xdir[k];
int y = j + ydir[k];
if (x >= 0 && x < xmax && y >= 0 && y < ymax && matrix[x][y]>matrix[i][j])
{
int maxlen = max(dp(matrix, x, y, tmp, xmax, ymax) + 1, tmp[i][j]);
tmp[i][j] = maxlen;
}
}
return tmp[i][j];
}
};
评论
发表评论