分享好友 编程语言首页 频道列表

C++ LeetCode542矩阵示例详解

C/C++教程  2023-02-09 10:110

LeetCode  542.01 矩阵

力扣题目链接:leetcode.cn/problems/01…

给定一个由 01 组成的矩阵 mat ,请输出一个大小相同的矩阵,其中每一个格子是 mat 中对应位置元素到最近的 0 的距离。

两个相邻元素间的距离为 1

示例 1:

C++ LeetCode542矩阵示例详解

输入:mat = [[0,0,0],[0,1,0],[0,0,0]]
输出:[[0,0,0],[0,1,0],[0,0,0]]

示例 2:

C++ LeetCode542矩阵示例详解

输入:mat = [[0,0,0],[0,1,0],[1,1,1]]
输出:[[0,0,0],[0,1,0],[1,2,1]] 

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • mat[i][j] is either 0 or 1.
  • mat 中至少有一个 0

方法一:广度优先搜索

首先遍历原始矩阵,找到所有的0,将其位置入队。

接着在队列不为空时,不断出队一个位置,并判断这个位置的上下左右是否被遍历过。

如果还没有被遍历过,那么就将新的位置入队。并将地图中新的位置的值修改为“出队位置的值 + 1”

原理:

所有的原始的0最终结果都是0。广度优先搜索就是在所有的“0”的位置中,走一步。这一步所到的位置就是“1”步能到达的位置。同理,“1”经过一步到达的位置就是“2”。最先到达的就是步数最少的。

  • 时间复杂度O(nm)
  • 空间复杂度O(nm)

AC代码

C++

typedef pair<int, int> pii;
const int direcitons[4][2] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& mat) {
        int n = mat.size(), m = mat[0].size();
        vector<vector<bool>> visited(n, vector<bool>(m, false));
        queue<pii> q;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!mat[i][j]) {
                    visited[i][j] = true;
                    q.push({i, j});
                }
            }
        }
        while (q.size()) {
            pii thisNode = q.front();
            q.pop();
            for (int d = 0; d < 4; d++) {
                int tx = thisNode.first + direcitons[d][0];
                int ty = thisNode.second + direcitons[d][1];
                if (tx >= 0 && tx < n && ty >= 0 && ty < m) {
                    if (!visited[tx][ty]) {
                        visited[tx][ty] = true;
                        mat[tx][ty] = mat[thisNode.first][thisNode.second] + 1;
                        q.push({tx, ty});
                    }
                }
            }
        }
        return mat;
    }
};

以上就是C++ LeetCode542矩阵示例详解的详细内容,更多关于C++ LeetCode542矩阵的资料请关注其它相关文章!

原文地址:https://juejin.cn/post/7173231256581177381

查看更多关于【C/C++教程】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
Aurelius vs mORMot vs EntityDAC Delphi 的 ORM框架
Aurelius vs mORMot vs EntityDAC   Delphi 的 ORM框架:http://www.tmssoftware.com/site/aurelius.asp#product-buy-onlinehttps://synopse.info/fossil/wiki/Synopse+OpenSourcehttps://www.devart.com/entitydac/download.htmlkbmMW  http://www.compo

0评论2023-02-09429

【Ruby】Mac gem的一些坑
前言自上一次升级MacOS系统后出现jekyll无法构建的问题,当时处理半天。谁知道最近又升级了MacOS,荒废博客多时,今天吝啬写了一篇准备发布,构建报错,问题重新。还是记录下,以防下次升级出问题。问题描述安装jekyll静态博客需要在Ruby环境下运行,于是参照

0评论2023-02-09384

iOS oc 调用 swift
如股票oc要调用swift里面的代码 需要包含固定这个头文件项目名称 LiqunSwiftDemo-Swift.h         #ProjectName#-Swift.h固定的写法swift 目的 是取代oc 但是 不会完全取代 只是前端的替换LiqunSwiftDemo-Swift 点进去 可以看到 所有的swift代码 都产生

0评论2023-02-09454

objective-c NSTimer 定时器
-(void)initTimer{//时间间隔NSTimeInterval timeInterval =3.0 ;//定时器repeats 表示是否需要重复,NO为只重复一次NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(mobileAnimation) userInfo:nil

0评论2023-02-09848

Objective-C KVC机制
Objective-C KVC机制http://blog.csdn.net/omegayy/article/details/7381301全部推翻重写一个版本,这是我在公司内做技术分享的文档总结,对结构、条理做了更清晰的调整。 1.    基本概念MODEL主要是英文文档里面经常出现的一些概念,讲解一下,方便英文

0评论2023-02-09690

objective-c 加号 减号 - +
“加号代表static”是错误的说法,可能跟你那样表达的人其实意思是:“前置加号的方法相当于Java 里面的静态方法”。在Oc中,方法分为类方法和实例方法。前置加号(+)的方法为类方法,这类方法是可以直接用类名来调用的,它的作用主要是创建一个实例。有人把

0评论2023-02-09705

ASP.NET MVC 操作AD 获取域服务器当前用户姓名和OU信息
#region 根据当前登录域账号 获取AD用户姓名和所在OU目录/// summary/// 根据当前登录域账号 获取AD用户姓名和所在OU目录/// /summary/// param name="searchUser"要搜索的当前用户名/param/// param name="paths"out返回该用户所在OU目录/param/// param nam

0评论2023-02-09366

swift和OC - 拆分数组 和 拆分字符串
1. 拆分数组 /// 根据 数组 截取 指定个数返回 多个数组的集合func splitArray( array: [Date], withSubSize subSize: Int) - [[Date]] {//数组将被拆分成指定长度数组的个数let count = array.count% subSize == 0 ? (array.count/ subSize) : (array.count

0评论2023-02-08588

objective-C 中类似于C#中trim的方法(去掉字符串前后空格)
在objective-c中去掉字符串前后空格的方法(类似于C#中的trim方法)如下:NSString *string = @" spaces in front and at the end "; NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterS

0评论2023-02-08584

objective-c 中如何使用 c++?
well, use .mm instead of .m to specify objective-c++ compiler 来源: http://www.philjordan.eu/article/strategies-for-using-c++-in-objective-c-projects If you're in a hurry and want to get straight to the solution of embedding C++ objects

0评论2023-02-08346

objective-c UIImageView 操作
// Do any additional setup after loading the view from its nib.NSLog(@"image vei");UIImageView*imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0,45.0,300,300)];imageView.image = [UIImage imageNamed:@"testimg.png"];//加载入图片[s

0评论2023-02-08473

[iphone开发]Objective-C学习笔记一: Objective-C 语言特性
一. Object-C 的前世今生Object-C语言由 Brad J.Cox于20世纪80年代早期设计,以SmallTalk为基础,建立在C语言之上。1988年,NeXT获得Object-C的授权,开发出了Object-C的语言库和一个名为NEXTSTEP的开发环境。1994年,NeXT公司与Sun 公司联合发布了一个

0评论2023-02-08399

Objective-C Content list
@import url("http://www.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css");@import url("/css/cuteeditor.css");@import url("http://www.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css");@import url("

0评论2023-02-08539

Objective-C 静态变量 使用方法
 Objective-C中静态变量使用方法是本文要介绍的内容,Objective-C 支持全局变量,主要有两种实现方式:第一种和C/C++中的一样,使用"extern"关键词;另外一种就是使用单例实现。(比如我们经常会把一个变量放在AppDelegate里面作为全局变量来访问,其中AppD

0评论2023-02-08465

Objective-C copy(转)
一、从面向对象到Objective-C概览copy1、面向对象:In object-oriented programming, object copying is creating a copy of an existing object, a unit of data in object-oriented programming. The resulting object is called an object copy or simply

0评论2023-02-08599

objective-c NSArray 列出指定文件目录列表
NSString *path=@"/usr/local";NSFileManager *myFileManager=[NSFileManager defaultManager];NSDirectoryEnumerator *myDirectoryEnumerator;NSArray *directoryContents;myDirectoryEnumerator=[myFileManager enumeratorAtPath:path];//列举目录内容NSLog

0评论2023-02-08773

Objective-C NSString 操作
  静态字符串 NSStringNSString *hello = @"hello"; // 声明NSString *append = [hello stringByAppendingString:@"world!"]; // 追加NSString *format = [NSString stringWithFormat:@"1 + 1 = %i", 2]; // 格式化NSString *helloStr = [[NSString all

0评论2023-02-08305

更多推荐