542 01 Matrix 01 矩阵
2024-09-30 03:15:57
给定一个由 0 和 1 组成的矩阵,找出每个元素到最近的 0 的距离。
两个相邻元素间的距离为 1 。
示例 1:
输入:
0 0 0
0 1 0
0 0 0
输出:
0 0 0
0 1 0
0 0 0
示例 2:
输入:
0 0 0
0 1 0
1 1 1
输出:
0 0 0
0 1 0
1 2 1
注意:
1.给定矩阵的元素个数不超过 10000。
2.给定矩阵中至少有一个元素是 0。
3.矩阵中的元素只在四个方向上相邻: 上、下、左、右。
详见:https://leetcode.com/problems/01-matrix/description/
C++:
class Solution {
public:
vector<vector<int>> updateMatrix(vector<vector<int>>& matrix)
{
int m = matrix.size(), n = matrix[0].size();
vector<vector<int>> res(m, vector<int>(n, INT_MAX - 1));
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (matrix[i][j] == 0)
{
res[i][j] = 0;
}
else
{
if (i > 0)
{
res[i][j] = min(res[i][j], res[i - 1][j] + 1);
}
if (j > 0)
{
res[i][j] = min(res[i][j], res[i][j - 1] + 1);
}
}
}
}
for (int i = m - 1; i >= 0; --i)
{
for (int j = n - 1; j >= 0; --j)
{
if (res[i][j] != 0 && res[i][j] != 1)
{
if (i < m - 1)
{
res[i][j] = min(res[i][j], res[i + 1][j] + 1);
}
if (j < n - 1)
{
res[i][j] = min(res[i][j], res[i][j + 1] + 1);
}
}
}
}
return res;
}
};
参考:https://www.cnblogs.com/grandyang/p/6602288.html
最新文章
- ASP.NET Core 在 JSON 文件中配置依赖注入
- 在Lingo中输入矩阵(通过Excel)
- VPS拨号主机自动拨号脚本(centos7)
- .Net分布式异常报警系统-服务端站点管理
- [转]C++模板学习
- SVN服务端启动解决方案(2013-12-10 记)
- 洛谷 P1886 滑动窗口
- std::function赋值的几种方法
- VritualBox 中Debian安装tool
- 【codevs】2292图灵机游戏
- THUSC2015
- Dotliquid使用Json模板变量
- 编程基础学习JS的入门教程
- EF性能检测工具MiniProfilerEF6的使用
- java23种设计模式之: 策略模式,观察者模式
- dispatch_barrier_async,加锁
- 键值对操作 之 combineByKey
- numpy常见属性、创建数组
- ASP.NET Core 1.0 中 EntityFramework 与 PostgreSQL 的使用
- 扫描神器--nmap