leetcode329,
Longest Increasing Path in a Matrix
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.
class Solution {
public:
int function(vector<vector<int> > & matrix, int i, int j, int rows, int cols, vector<vector<int> > & dp)
{
if (dp[i][j] != -1)
{
return dp[i][j];
}
int left = 0;
int right = 0;
int up = 0;
int down = 0;
//left
if (j != 0 && matrix[i][j - 1] > matrix[i][j])
{
left = function(matrix, i, j - 1, rows, cols, dp);
}
//right
if (j != cols - 1 && matrix[i][j + 1] > matrix[i][j])
{
right = function(matrix, i, j + 1, rows, cols, dp);
}
//up
if (i != 0 && matrix[i - 1][j] > matrix[i][j])
{
up = function(matrix, i - 1, j, rows, cols, dp);
}
//down
if (i != rows - 1 && matrix[i + 1][j] > matrix[i][j])
{
down = function(matrix, i + 1, j, rows, cols, dp);
}
dp[i][j] = max(max(left, right), max(up, down)) + 1;
return dp[i][j];
}
int longestIncreasingPath(vector<vector<int>>& matrix) {
if (matrix.size() == 0)
{
return 0;
}
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector<int> > dp(rows, vector<int>(cols, -1));
int max_result = 0;
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
{
max_result = max(max_result, function(matrix, i, j, rows, cols, dp));
}
}
return max_result;
}
};