• 网格bfs,LeetCode 2684. 矩阵中移动的最大次数


    一、题目

    1、题目描述

    给你一个下标从 0 开始、大小为 m x n 的矩阵 grid ,矩阵由若干  整数组成。

    你可以从矩阵第一列中的 任一 单元格出发,按以下方式遍历 grid :

    • 从单元格 (row, col) 可以移动到 (row - 1, col + 1)(row, col + 1) 和 (row + 1, col + 1) 三个单元格中任一满足值 严格 大于当前单元格的单元格。

    返回你在矩阵中能够 移动 的 最大 次数。

    2、接口描述

    ​cpp
    1. class Solution {
    2. public:
    3. int maxMoves(vectorint>>& grid) {
    4. }
    5. };

    python3

    1. class Solution:
    2. def maxMoves(self, grid: List[List[int]]) -> int:

    3、原题链接

    2684. 矩阵中移动的最大次数


    二、解题报告

    1、思路分析

    我们将第一列的位置入队,然后在网格上进行bfs

    对于每个当前位置可以抵达的位置,我们就将其入队,然后记得标记

    2、复杂度

    时间复杂度: O(mn)空间复杂度:O(mn)

    3、代码详解

    ​cpp
    1. class Solution {
    2. public:
    3. typedef pair<int, int> PII;
    4. static constexpr int dst[3][2] = {{-1, 1}, {0, 1}, {1, 1}};
    5. int maxMoves(vectorint>>& g) {
    6. queue q;
    7. int m = g.size(), n = g[0].size(), ret = 0;
    8. vectorbool>> vis(m, vector<bool>(n));
    9. for(int i = 0; i < m; i++) q.emplace(i, 0);
    10. while(q.size()){
    11. for(int i = 0, ed = q.size(); i < ed; i++){
    12. auto [x, y] = q.front(); q.pop();
    13. for(int j = 0, nx, ny; j < 3; j++){
    14. nx = x + dst[j][0], ny = y + dst[j][1];
    15. if(nx < 0 || ny < 0 || nx >= m || ny >= n) continue;
    16. if(vis[nx][ny] || g[x][y] >= g[nx][ny]) continue;
    17. q.emplace(nx, ny), vis[nx][ny] = 1;
    18. }
    19. }
    20. ret += !q.empty();
    21. }
    22. return ret;
    23. }
    24. };
    python3
    1. class Solution:
    2. def maxMoves(self, g: List[List[int]]) -> int:
    3. m, n = len(g), len(g[0])
    4. for i in range(m):
    5. g[i][0] *= -1
    6. for j in range(n - 1):
    7. for i, row in enumerate(g):
    8. if row[j] > 0:
    9. continue
    10. for k in i - 1, i, i + 1:
    11. if 0 <= k < m and g[k][j + 1] > -row[j]:
    12. g[k][j + 1] *= -1
    13. if all(row[j + 1] > 0 for row in g):
    14. return j
    15. return n - 1

  • 相关阅读:
    二进制部署MySQL8.0
    ESP32S3在VScode中使用USB口调试
    OkHttp报unexcepted end of stream on...错误分析
    腾讯云16核服务器性能测评_轻量和CVM配置大全
    索引的数据结构(3)
    2022年你必须要会的微前端 -(源码篇)
    node.js学习笔记 10包管理器
    第八章:网络设备文件管理)
    一文读懂vue3的Pinia
    计算机组成体系
  • 原文地址:https://blog.csdn.net/EQUINOX1/article/details/136767037