2020年5月4日
LeetCode 329. Longest Increasing Path in a Matrix
C++, LeetCode, 算法, 编程
0 Comments
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.
矩阵中的每个位置都可以上下左右移动,然后计算出一条递增的最长路径。
这道题的解法要用递归和DP来解,用DP的原因是为了提高效率,避免重复运算。我们需要维护一个二维动态数组dp,其中dp[i][j]表示数组中以(i,j)为起点的最长递增路径的长度,初始将dp数组都赋为0,当我们用递归调用时,遇到某个位置(x, y), 如果dp[x][y]不为0的话,我们直接返回dp[x][y]即可,不需要重复计算。我们需要以数组中每个位置都为起点调用递归来做,比较找出最大值。在以一个位置为起点用DFS搜索时,对其四个相邻位置进行判断,如果相邻位置的值大于上一个位置,则对相邻位置继续调用递归,并更新一个最大值,搜素完成后返回即可。代码如下:
class Solution {
public:
vector<vector<int>> dirs = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
int longestIncreasingPath(vector<vector<int>>& matrix) {
if(matrix.empty())
return 0;
int row_size = matrix.size();
int col_size = matrix[0].size();
int max_len = 0;
vector<vector<int>> dp(row_size, vector<int>(col_size, 0));
for(int i=0; i < row_size; i++)
{
for(int j=0; j < col_size; j++)
{
max_len = max(max_len, dfs(matrix, dp, i, j));
}
}
return max_len;
}
int dfs(vector<vector<int>>& matrix, vector<vector<int>> &dp, int i, int j)
{
if(dp[i][j])
return dp[i][j];
int max_len = 1;
int row_size = matrix.size();
int col_size = matrix[0].size();
for(auto pos : dirs)
{
int x = i + pos[0];
int y = j + pos[1];
if(x < 0 || x >= row_size || y < 0 || y >= col_size || matrix[i][j] >= matrix[x][y])
continue;
max_len = max(max_len, 1+dfs(matrix, dp, x ,y));
}
dp[i][j] = max_len;
return max_len;
}
};
总结:通过此道题目,收货点有2个地方:
a.在每个位置可以上下左右移动,然后在处理这4个位置的时候,不必相同代码写4遍,定义一个以当前位置为中心的相对距离数组,然后遍历这个数组即可完成对4个位置的遍历。
b.因为在每个位置只可以上下左右4个位置移动,所以循环控制放在dfs外面,通过外面传入中心位置。
c.动态规划在这里提高效率,避免重复计算。