LeetCode 329: Longest Increasing Path in a Matrix

来源:互联网 发布:录制手机屏幕视频软件 编辑:程序博客网 时间:2024/05/29 09:36

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
原创粉丝点击