landscapemi的博客

# leetcode： Memoization：Longest Increasing Path in a Matrix（329）

https://leetcode.com/problems/longest-increasing-path-in-a-matrix/

class Solution {
public:
bool checkRange(vector<vector<int> >& matrix, int x, int y) {
int n = matrix.size(), m = matrix[0].size();
if(x < 0 || y < 0 || x >= n || y >= m)  return false;
return true;
}

int dfs(vector<vector<int> >& matrix, vector<vector<int> >& dp, vector<vector<bool> >& vis, vector<vector<int> >& dir, int x, int y) {
if(dp[x][y])  return dp[x][y];

int MAX = -1;
for(int i=0; i<dir.size(); ++i) {
int nx = x + dir[i][0], ny = y + dir[i][1];
if(checkRange(matrix, nx, ny) && !vis[nx][ny] && matrix[nx][ny] > matrix[x][y]) {
vis[nx][ny] = true;
MAX = max(MAX, dfs(matrix, dp, vis, dir, nx, ny) + 1);
vis[nx][ny] = false;
}
}

if(MAX == -1) return 1;
dp[x][y] = MAX;
return dp[x][y];
}

int longestIncreasingPath(vector<vector<int>>& matrix) {
int n = matrix.size();
if(n == 0)  return 0;

int m = matrix[0].size();
vector<vector<int> > dp(n, vector<int>(m, 0));
vector<vector<bool> > vis(n, vector<bool>(m, false));
vector<vector<int> > dir(4);
dir[0].push_back(-1);  dir[0].push_back(0);
dir[1].push_back(0);  dir[1].push_back(1);
dir[2].push_back(1);  dir[2].push_back(0);
dir[3].push_back(0);  dir[3].push_back(-1);

int res = -1;
for(int i=0; i<n; ++i) {
for(int j=0; j<m; ++j) {
vis[i][j] = true;
dp[i][j] = dfs(matrix, dp, vis, dir, i, j);
res = max(res, dp[i][j]);
vis[i][j] = false;
}
}

return res;
}
};

#### leetcode笔记：Longest Increasing Path in a Matrix

2016-02-21 23:41:45

#### leetcode 解题记录 Longest Increasing Path in a Matrix

2016-01-28 13:53:56

#### Longest Increasing Path in a Matrix

2016-01-31 00:26:08

#### 算法分析课每周练习 Longest Increasing Path in a Matrix

2017-06-27 01:03:22

#### [LeetCode] Longest Increasing Path in a Matrix

2016-01-28 20:49:30

#### leetcode 300. Longest Increasing Subsequence-最长子序列|动态规划

2016-06-02 20:17:05

#### 673. Number of Longest Increasing Subsequence

2017-09-10 11:03:51

#### LeetCode 300. Longest Increasing Subsequence 解题报告

2016-02-16 19:35:07

#### 【LEETCODE】300-Longest Increasing Subsequence [Python]

2016-01-07 20:36:24

#### LeetCode #329: Longest Increasing Path in a Matrix

2016-08-31 20:45:13