算法设计与分析-Week5

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:

Input: nums =
[
 [9,9,4],
 [6,6,8],
 [2,1,1]
]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: nums =
[
 [3,4,5],
 [3,2,6],
 [2,2,1]
]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

解题思路

本题要在一个矩阵中找到一个最长的递增序列的长度。
用一个与所给矩阵大小相同的矩阵path,其中该矩阵的每个元素代表从该元素出发所能走出的最长递增序列的长度,那么只要记录这个矩阵的最大元素longest即为题目所求。遍历所给矩阵的每个元素,从该元素出发作DFS,每个元素有四个方向可以走,走之前先判断下一个位置是否越界以及下一个元素是否大于当前元素,如果是则对下一个位置进行DFS;如果当前位置的path值不为0,则说明当前位置已经经过DFS,直接返回即可;如果当前位置不存在满足条件的下一个位置,则说明当前位置是附近最大的一个元素,其path值为1。

源代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int dir[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty()) return 0;
int longest = 0;
int m = matrix.size();
int n = matrix[0].size();
vector<vector<int>> path;
for(int i = 0; i < m; i++) {
vector<int> temp(n, 0);
path.push_back(temp);
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
longest = max(longest, dfs(matrix, i, j, path));
}
}
return longest;
}
int dfs(vector<vector<int>>& matrix, int i, int j, vector<vector<int>>& path) {
if(path[i][j] != 0) return path[i][j];
int longest = 1;
int m = matrix.size();
int n = matrix[0].size();
for(int k = 0; k < 4; k++){
int x = i + dir[k][0];
int y = j + dir[k][1];
if(x >= 0 && x < m && y >=0 && y < n && matrix[x][y] > matrix[i][j]) {
int len = 1 + dfs(matrix, x, y, path);
longest = max(longest, len);
}
}
path[i][j] = longest;
return longest;
}
};
0%