LeetCode 329: Longest Increasing Path in a Matrix

329. Longest Increasing Path in a Matrix

Difficulty: Hard
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.

思路

最简单的想法是,把每个数都当成路径的起始点试试,找它的最长递增路径,再比较哪个数的路径最长。
实现时,必定会有一个和矩阵同大小的矩阵来记录每个数的访问情况。
但是如果只是单纯地记录是否被访问的话,有些递增路径将会被多次重复遍历,改为记录该位置可达到的最远递增距离,可避免许多不必要的遍历。

代码

[C++]

class Solution {
public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        int row = matrix.size();
        if (row == 0)
            return 0;
        int column = matrix[0].size();
        vector<vector<int>> visited(row, vector<int>(column, 0));
        int res = 0;
        int temp = 0;
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < column; ++j) {
                temp = IncreasingPathCore(matrix, visited, row, column, i, j);
                res = max(res, temp);
            }
        }
        return res;
    }
    int IncreasingPathCore(vector<vector<int>>& matrix, vector<vector<int>> &visited, int rows, int columns, int i, int j){
        if (visited[i][j])
            return visited[i][j];
        int up = 0;
        if (i > 0 && matrix[i][j] < matrix[i - 1][j])
            up = IncreasingPathCore(matrix, visited, rows, columns, i - 1, j);
        int down = 0;
        if (i < rows - 1 && matrix[i][j] < matrix[i + 1][j])
            down = IncreasingPathCore(matrix, visited, rows, columns, i + 1, j);
        int left = 0;
        if (j > 0 && matrix[i][j] < matrix[i][j - 1])
            left = IncreasingPathCore(matrix, visited, rows, columns, i, j - 1);
        int right = 0;
        if (j < columns - 1 && matrix[i][j] < matrix[i][j + 1])
            right = IncreasingPathCore(matrix, visited, rows, columns, i, j + 1);
        visited[i][j] = max(max(up, down), max(left, right)) + 1;
        return visited[i][j];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值