329 Longest Increasing Path in a Matrix
很普通的做法,竟然击败了 98%的提交者
![[汗]](/static/emoticons/u6c57.png)
class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
raw = matrix.size();
if (raw == 0) return 0;
col = matrix[0].size();
if (col == 0) return 0;
p = &matrix;
counts = new int[raw * col];
memset(counts, 0, raw * col * sizeof(int));
int result = 1;
for (size_t i = 0; i < raw; ++i)
{
for (size_t j = 0; j < col; ++j)
{
int temp = path(i, j);
result = result < temp ? temp : result;
}
}
delete []counts;
return result;
}
int path(int i, int j)
{
int t = counts[i * col + j];
if (t != 0) return t;
t = 1;
//up
if (i - 1 >= 0)
{
if ((*p)[i - 1][j] > (*p)[i][j])
{
int n = path(i - 1, j);
t = t <= n ? n + 1 : t;
}
}
//down
if (i + 1 < raw)
{
if ((*p)[i + 1][j] > (*p)[i][j])
{
int n = path(i+1, j);
t = t <= n ? n + 1 : t;
}
}
// left
if (j - 1 >= 0)
{
if ((*p)[i][j - 1] > (*p)[i][j])
{
int n = path(i, j - 1);
t = t <= n ? n + 1 : t;
}
}
//right
if (j + 1 < col)
{
if ((*p)[i][j + 1] > (*p)[i][j])
{
int n = path(i, j + 1);
t = t <= n ? n + 1 : t;
}
}
counts[i * col + j] = t;
return t;
}
private:
int raw;
int col;
int * counts;
vector<vector<int>> *p;
};