每日一练——矩阵中的最大递增路径

题目描述:

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.

解题思路:

对于矩阵中的每一个数字,用深度优先遍历寻找最比当前数字大的数字,对于已经走过的数字,将其置位为INT_MIN,下次经过这个数字可以直接不用考虑。如果走到某个位置,其上下左右的数字都比当前数字小,那么说明已经无路可走,那么就得进行回溯,回溯的过程中必须将之前置位为INT_MIN的数字恢复为初始数字。

代码如下:

class Solution {
private:
    int curLen;
    int maxLen;
    int row;
    int col;
public:
    void Move(vector<vector<int> >& matrix, int x, int y)
    {
        int cur = matrix[x][y];
        matrix[x][y] = INT_MIN;
        curLen++;
        if (curLen > maxLen)
        {
            if (curLen == 8)
            {
                curLen = curLen;
            }
            maxLen = curLen;
        }
        if (y + 1 < col && matrix[x][y+1] > cur)
        {
            Move(matrix, x, y+1);
        }
        if (y - 1 >= 0 && matrix[x][y-1] > cur)
        {
            Move(matrix, x, y-1);
        }
        if (x + 1 < row && matrix[x+1][y] > cur)
        {
            Move(matrix, x+1, y);
        }
        if (x - 1 >= 0 && matrix[x-1][y] > cur)
        {
            Move(matrix, x-1, y);
        }
        matrix[x][y] = cur;
        curLen--;
    }
    int longestIncreasingPath(vector<vector<int> >& matrix) {
        if (matrix.empty()||matrix[0].empty()) return 0;
        row = matrix.size();
        col = matrix[0].size();

        for (int i = 0; i < row; i++)
        {
            for (int j = 0; j < col; j++)
            {
                curLen = 0;
                Move(matrix, i, j);
            }
        }

        return maxLen;
    }
};


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值