LeetCode #329
Interview

# Description:

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:

``````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.
``````

Note: 其实就是2D的DP。

# Code:

``````class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty()) return 0;

int m=matrix.size();
int n=matrix[0].size();

vector<vector<int>> DP(m, vector<int>(n, 0));

int max_path=0;

for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(DP[i][j]==0){
max_path = max(max_path, DFS(matrix, i, j, DP));
}
}
}

return max_path;
}

int DFS(const vector<vector<int>>& matrix, int i, int j, vector<vector<int>>& DP){
int m=matrix.size();
int n=matrix[0].size();

if(DP[i][j]!=0) return DP[i][j];

vector<pair<int, int>> move={{-1,0}, {0,1}, {1,0}, {0,-1}};

int val=0;

for(auto e: move){
int i_next = i+e.first;
int j_next = j+e.second;

if(i_next>=0 && i_next<m && j_next>=0 && j_next<n && matrix[i][j]<matrix[i_next][j_next])
val = max(val, DFS(matrix, i_next, j_next, DP));
}
DP[i][j] = val+1;

return DP[i][j];
}
};
``````

``````class Solution {
public:
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty()) return 0;

int m=matrix.size();
int n=matrix[0].size();

vector<vector<int>> DP(m, vector<int>(n, 0));

int max_path=0;

for(int i=0; i<m; ++i){
for(int j=0; j<n; ++j){
if(DP[i][j]==0){
max_path = max(max_path, DFS(matrix, matrix[i][j]-1, i, j, DP)); // Assume the pre_val is matrix[i][j]-1, otherwise always return 0;
}
}
}

return max_path;
}

int DFS(const vector<vector<int>>& matrix, int pre_val, int i, int j, vector<vector<int>>& DP){
int m=matrix.size();
int n=matrix[0].size();

if(i<0 || i>=m || j<0 || j>=n) return 0;

if(matrix[i][j]<=pre_val) return 0;

if(DP[i][j]!=0) return DP[i][j];

vector<pair<int, int>> move={{-1,0}, {0,1}, {1,0}, {0,-1}};

int val=0;

for(auto e: move){
int i_next = i+e.first;
int j_next = j+e.second;
val = max(val, DFS(matrix, matrix[i][j], i_next, j_next, DP));
}
DP[i][j] = val+1;

return DP[i][j];
}
};
``````