1、题目描述
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:
Input: nums =
[
[9,9,4],
[6,6,8],
[2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9]
.
2、解题思路:
转载:Herbert_Zero
DFS+记忆化搜索
从起点开始遍历矩阵,递归寻找其最长递增路径。
定义辅助数组record,用于记录已经搜索过的矩阵元素的数据,如record[x][y]存储了从坐标(x, y)出发的最长递增路径长度。
之后,进行深度优先搜索。逐一检查某个元素的四个方向,并继续从所有可能出现最长路径的方向上进行搜索。
当遇到record[x][y]已算出的情况,直接返回record[x][y],减少运算量。
3、示例代码:
class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { if (matrix.size() == 0) return 0; vector<int> temp(matrix[0].size(), 0); vector<vector<int>> record(matrix.size(), temp); int longest = 0; for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[0].size(); j++) { longest = max(longest, DFS(matrix, record, i, j, -1)); } } return longest; } int DFS(vector<vector<int> >& matrix, vector<vector<int> >& record, int x, int y, int lastVal) { if (x < 0 || y < 0 || x >= matrix.size() || y >= matrix[0].size()) return 0; if (matrix[x][y] > lastVal) { if (record[x][y] != 0) return record[x][y]; int left = DFS(matrix, record, x - 1, y, matrix[x][y]); int right = DFS(matrix, record, x + 1, y, matrix[x][y]); int up = DFS(matrix, record, x, y + 1, matrix[x][y]); int bottom = DFS(matrix, record, x, y - 1, matrix[x][y]); record[x][y] = max(left, max(right, max(up, bottom))) + 1; return record[x][y]; } return 0; } };