给定一个由 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

最新文章

  1. ASP.NET Core 在 JSON 文件中配置依赖注入
  2. 在Lingo中输入矩阵(通过Excel)
  3. VPS拨号主机自动拨号脚本(centos7)
  4. .Net分布式异常报警系统-服务端站点管理
  5. [转]C++模板学习
  6. SVN服务端启动解决方案(2013-12-10 记)
  7. 洛谷 P1886 滑动窗口
  8. std::function赋值的几种方法
  9. VritualBox 中Debian安装tool
  10. 【codevs】2292图灵机游戏
  11. THUSC2015
  12. Dotliquid使用Json模板变量
  13. 编程基础学习JS的入门教程
  14. EF性能检测工具MiniProfilerEF6的使用
  15. java23种设计模式之: 策略模式,观察者模式
  16. dispatch_barrier_async,加锁
  17. 键值对操作 之 combineByKey
  18. numpy常见属性、创建数组
  19. ASP.NET Core 1.0 中 EntityFramework 与 PostgreSQL 的使用
  20. 扫描神器--nmap

热门文章

  1. FindBugs规则整理
  2. CyclicBarrier及CountDownLatch的使用
  3. CISCO-路由器交换机IOS被删,恢复方法
  4. HDU1525 Euclid&#39;s Game
  5. jquery跨域3
  6. AndroidStudio删除项目
  7. HDU 1627 Krypton Factor
  8. Thief in a Shop
  9. matlab白底换红底
  10. UVa 1349 Optimal Bus Route Design (最佳完美匹配)