leetcode2684--矩阵中移动的最大次数

1. 题意

矩阵中一个位置只能从左上一、左、左下一格子转移而来,且当前值一定大于转移之前的值;

求从第一列开始的最大转移步数。

矩阵中移动的最大次数

2. 题解

  • 思路
    由于状态只能从左向右转移,所以同一个位置被搜索到后,第一列其他位置再搜索到它的距离一定相等。题目求得是第一列转移到其他位置的最大次数,我们需要把第一列置0,其他列置
    MINVAL。使得只有从第一列转移的才能使得值为正数。
cpp 复制代码
class Solution {
public:
    struct Dir {
        constexpr static int dir[][2] = {
            {1,-1},{0,-1},{-1,-1}
        };
    };
    int maxMoves(vector<vector<int>>& grid) {
        
        int w = grid[0].size();
        int h = grid.size();
        int MIN_VAL = -2000;
        int ans = 0;
        vector<vector<int>> dp(h, vector<int>(w, MIN_VAL));


        for (int i = 0;i < h; ++i)
            dp[i][0] = 0;

        for (int i = 1; i < w; ++i) {
            for (int j = 0;j < h; ++j) {

                for (auto &d:Dir::dir){
                    int px = j + d[0];
                    int py = i + d[1];

                    if (px < 0 || py < 0 || px > h - 1 || py > w - 1)
                        continue; 
                    if (grid[px][py] >= grid[j][i])
                        continue;

                    dp[j][i] = max(dp[j][i], dp[px][py] + 1);
                    
                }
                ans = max(dp[j][i],ans);
            }
        }


        return ans;
    }
};
  • 记忆化搜索
cpp 复制代码
class Solution {
public:
    struct Dir {
        constexpr static int dir[][2] = {
            {-1,1},{0,1},{1,1}
        };
    };

    int dfs(int i, int j,
    vector<vector<int>> &mem, const vector<vector<int>> &grid)
    {
        int m = mem.size();
        int n = mem[0].size();

        if (mem[i][j] != -1)
            return  mem[i][j];

        int ans = 0;

        for (auto c:Dir::dir) {
            int nx = i + c[0];
            int ny = j + c[1];

            if ( nx < 0 || nx > m - 1 || ny < 0 || ny > n - 1)
                continue;
            if (grid[i][j] >=grid[nx][ny])
                continue;
            
            int t = dfs(nx,ny, mem, grid);
            ans = max(ans, 1 + t);
        }

        return mem[i][j] = ans;
    }

    int maxMoves(vector<vector<int>>& grid) {
        
        int ans = 0;

        int h = grid.size();
        int w = grid[0].size();
        vector<vector<int>> mem(h, vector<int>(w, -1));


        for (int i = 0;i < h; ++i) {
            ans = max(dfs(i, 0, mem, grid), ans);
        }

        return ans;
    }
};
相关推荐
LluckyYH13 小时前
代码随想录Day 58|拓扑排序、dijkstra算法精讲,题目:软件构建、参加科学大会
算法·深度优先·动态规划·软件构建·图论·dfs
吱吱鼠叔17 小时前
MATLAB数据文件读写:2.矩阵数据读取
数据库·matlab·矩阵
￴ㅤ￴￴ㅤ9527超级帅17 小时前
LeetCode hot100---数组及矩阵专题(C++语言)
c++·leetcode·矩阵
海涛高软17 小时前
osg 矩阵相关
线性代数·矩阵
herobrineAC2 天前
以矩阵的视角解多元一次方程组——矩阵消元
线性代数·矩阵
ganjiee00073 天前
力扣(leetcode)每日一题 983 最低票价 |动态规划
算法·leetcode·动态规划
EQUINOX13 天前
思维+贪心,CF 1210B - Marcin and Training Camp
算法·数学建模·动态规划
_GR3 天前
每日OJ题_牛客_JOR26最长回文子串_C++_Java
java·数据结构·c++·算法·动态规划
正义的彬彬侠4 天前
单位向量的定义和举例说明
人工智能·线性代数·机器学习·矩阵
源代码•宸4 天前
小米2025届软件开发工程师(C/C++/Java)(编程题AK)
c语言·c++·经验分享·算法·动态规划