当前位置: 首页 > news >正文

leetcode0542. 01 矩阵-medium

1 题目:01 矩阵

官方标定难度:中

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

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

示例 1:

在这里插入图片描述

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

示例 2:

在这里插入图片描述

输入: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

2 solution

从起点开始广度优先搜索。

代码

class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>> &mat) {/** 广度优先*/int m = mat.size();int n = mat[0].size();vector<vector<int>> res(m, vector<int>(n, -1));queue<int> x;queue<int> y;for (int i = 0; i < m; i++) {for (int j = 0; j < n; j++) {if (mat[i][j] == 0) {res[i][j] = 0;x.push(i);y.push(j);}}}int dx[] = {1, -1, 0, 0};int dy[] = {0, 0, 1, -1};while (!x.empty()) {int r = x.front();int c = y.front();x.pop(), y.pop();for (int i = 0; i < 4; i++) {int rr = r + dx[i];int cc = c + dy[i];if (rr < 0 || rr >= m || cc < 0 || cc >= n || res[rr][cc] != -1) continue;res[rr][cc] = res[r][c] + 1;x.push(rr);y.push(cc);}}return res;
}};

结果

在这里插入图片描述

http://www.xdnf.cn/news/301987.html

相关文章:

  • 第八章,STP(生成树协议)
  • [论文阅读]Deep Cross Network for Ad Click Predictions
  • C# 使用SunnyUI控件 (VS 2019)
  • 上市公司-企业上下游供应链数据(2003-2023年)-社科数据
  • 解释 NestJS 的架构理念(例如,模块化、可扩展性、渐进式框架)
  • 【MongoDB篇】MongoDB的事务操作!
  • VBA ListBox/ComboBox 响应鼠标滚轮操作
  • Java中常见的问题
  • Jupyter Notebook为什么适合数据分析?
  • [监控看板]Grafana+Prometheus+Exporter监控疑难排查
  • UE5 使用插槽和物理约束对角色新增的饰品添加物理效果
  • Maven依赖未生效问题
  • Houdini制作烟雾消散并导入UE5
  • UE5 Daz头发转Blender曲线再导出ABC成为Groom
  • 基于Blender的AI插件——2D图片生成3D模型
  • Python 中的数据结构介绍
  • LangChain:大语言模型应用的“瑞士军刀”入门指南
  • Sublime Text快速搭建Lua语言运行环境
  • vue3中解决 return‘ inside ‘finally‘ block报错的问题
  • 【AI】如何自己训练AI大模型
  • IP-Adapter
  • LeetCode 每日一题 2025/4/28-2025/5/4
  • 华为云短信接入实现示例
  • c#OdbcDataReader的数据读取
  • Blender 初学者指南 以及模型格式怎么下载
  • FPGA----基于ZYNQ 7020实现petalinux并运行一个程序
  • 赛灵思 XCZU11EG-2FFVC1760I XilinxFPGAZynq UltraScale+ MPSoC EG
  • 探索Hello Robot开源移动操作机器人Stretch 3的新技术亮点与市场定位
  • 在 GitLab 中部署Python定时任务
  • 在与大语言模型交互中的礼貌现象:技术影响、社会行为与文化意义的多维度探讨