【LeetCode 329】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.

题目大意:

找一个矩阵里的最长递增序列的长度,可以向上、下、左、右四个方向移动。

思路:

和迷宫类似的一个dfs,以每个没搜索过的点为起点搜。

代码:

class Solution {
public:
    int dir[4][2] = {{0, 1},  {0, -1},  {1, 0},  {-1, 0}};

    int longestIncreasingPath(vector<vector<int> > const &matrix) {
        if (matrix.empty() || matrix[0].empty()) return 0;
        int n = matrix.size();
        int m = matrix[0].size();

        vector<vector<int> > pnum(n+10, vector<int>(m+10, -1));

        int ans = 0;

        for (int i=0; i<n; ++i) {
            for (int j=0; j<m; ++j) {
                // cout << i << " " << j << endl;
                if (pnum[i][j] != -1){
                    ans = max(ans, pnum[i][j]);
                }
                else {
                    ans = max(ans, findPath(i, j, matrix, pnum));
                }
            }
        }
        return ans+1;
    }

    int findPath(int x, int y, vector<vector<int> >  const &matrix, vector<vector<int> > &pnum) {
        if (pnum[x][y] != -1) return pnum[x][y];
        int temp = 0;
        int n = matrix.size(), m = matrix[0].size();

        for (int i=0; i<4; ++i) {
            int xx = x + dir[i][0];
            int yy = y + dir[i][1];
            if (xx < 0 || yy < 0 || xx >= n || yy >= m) continue;
            if (matrix[xx][yy] > matrix[x][y]) {
                temp = max(temp, findPath(xx, yy, matrix, pnum) + 1);
            }
        }
        pnum[x][y] = temp;
        return pnum[x][y];
    }
};

MLE,找了好久好久的bug。发现是传参。是应该好好学习C++了。

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/88187948