# [leetcode] 329. 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 longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.size() == 0)return 0;
int max_value = 0;
this->matrix = matrix;
row = matrix.size();
col = matrix[0].size();
this->DP = vector<vector<int>>(row, vector<int>(col, 0));
directions = {{0,1}, {0,-1}, {-1,0}, {1, 0}};
for(int i = 0; i < row; i++)
for(int j = 0; j < col; j++) {
int res = backTracking(i, j);
max_value = max(max_value, res);
}
return max_value;
}

int backTracking(int x, int y) {
if(DP[x][y])return DP[x][y];
int result = 0;
for(auto& direction:directions) {
int nextX = x + direction[0];
int nextY = y + direction[1];
if(nextX < 0 || nextX >= row || nextY < 0 || nextY >= col || matrix[x][y] >= matrix[nextX][nextY])continue;
int res = backTracking(nextX, nextY);
result = max(result, res);
}
DP[x][y] = ++result;
return result;
}
private:
vector<vector<int>> matrix;
vector<vector<int>> DP;
int row;
int col;
vector<vector<int>> directions;
};
• 本文已收录于以下专栏：

## [LeetCode] Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path.From each cell, you can eith...
• u011331383
• 2016年01月28日 20:49
• 2403

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

• liyuefeilong
• 2016年02月21日 23:41
• 1697

## LeetCode-329.Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path. From each cell, you can ...
• zmq570235977
• 2016年06月05日 13:38
• 443

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

Given an integer matrix, find the length of the longest increasing path. From each cell, you can ...
• sbitswc
• 2016年02月21日 08:49
• 1434

## 【Leetcode】Longest Increasing Path in a Matrix

• yeqiuzs
• 2016年05月31日 15:38
• 2409

## Longest Increasing Path in a Matrix

Given an integer matrix, find the length of the longest increasing path. From each cell, you can ...
• beiyetengqing
• 2016年01月31日 00:26
• 977

## [leetcode] - 329. Longest Increasing Path in a Matrix

• decaywood
• 2016年01月26日 19:58
• 242

## 【LeetCode】329. Longest Increasing Path in a Matrix

• Artemis96
• 2016年10月02日 13:54
• 124

## [leetcode]329. Longest Increasing Path in a Matrix

• xiaocong1990
• 2017年06月28日 21:28
• 84

## 329. Longest Increasing Path in a Matrix LeetCode

• youthinkwu
• 2016年02月16日 19:35
• 153

举报原因： 您举报文章：[leetcode] 329. Longest Increasing Path in a Matrix 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)