542. 01 Matrix
来源:互联网 发布:航仕科技 知乎 编辑:程序博客网 时间:2024/05/22 12:40
Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.Example 1:
Input:0 0 00 1 00 0 0Output:0 0 00 1 00 0 0Example 2:
Input:0 0 00 1 01 1 1Output:0 0 00 1 01 2 1Note:
- The number of elements of the given matrix will not exceed 10,000.
- There are at least one 0 in the given matrix.
- The cells are adjacent in only four directions: up, down, left and right.
这道题要熟悉坐标型bfs的坐标表示,和越界情况的判断。同时这道题如果按以前的方法,一个点压如queue,然后bfs的话,会超时。对这道题进行分析
可以将所有为0的点都存入queue,同时将matrix里所有为1的点的值重设置为一个很大的数。对这些都为0的点进行bfs
class Solution { public int[][] updateMatrix(int[][] matrix) { int m = matrix.length; int n = matrix[0].length; Queue<int[]> queue = new LinkedList<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) { queue.offer(new int[] {i, j}); } else { matrix[i][j] = Integer.MAX_VALUE; } } } int[][] dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; while (!queue.isEmpty()) { int[] cell = queue.poll(); for (int[] d : dirs) { int r = cell[0] + d[0]; int c = cell[1] + d[1]; if (r < 0 || r >= m || c < 0 || c >= n || matrix[r][c] <= matrix[cell[0]][cell[1]] + 1) continue; queue.add(new int[] {r, c}); matrix[r][c] = matrix[cell[0]][cell[1]] + 1; } } return matrix; }}
阅读全文0 0
- 542. 01 Matrix
- Leetcode-542. 01 Matrix
- 542. 01 Matrix
- [LeetCode]542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- leetcode 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix 题解
- [leetcode]542. 01 Matrix
- 【LeetCode】542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix
- 542. 01 Matrix [LeetCode]
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- 使用插件 aspectj-maven-plugin 织入 AspectJ AOP
- zoj3609_Modular Inverse(扩展欧几里得/naked)
- C++ 静态变量
- 多线程基础
- 震惊,程序员小编平时竟然上这种网站
- 542. 01 Matrix
- Linux查看GPU信息和使用情况
- Oracle数据库知识整理
- 版本控制工具(svn,git)
- 计算机英语基本词汇
- Javac 编译器
- 打开Eclipse提示“The default workspace “xxxx” is in use or cannot be created Please choose a different on
- 回顾大一·C语言编程11.1(2)+11.2(1)(2)(2)(3)①(3)②+11.3(1)(2)+11.4(1)①②+11.4(2)
- java内存模型JMM
原创粉丝点击
热门IT博客
热门问题
老师的惩罚
人脸识别
我在镇武司摸鱼那些年
重生之率土为王
我在大康的咸鱼生活
盘龙之生命进化
天生仙种
凡人之先天五行
春回大明朝
姑娘不必设防,我是瞎子
小米5不支持ar怎么办
WIN7没按驱动怎么办
百度地图定错位怎么办
手机qq闪图裂了怎么办
QQ聊天闪图裂了怎么办
花呗没用完的钱怎么办
今借到逾期不还怎么办
爱课程怎么打不开怎么办
小孩皮肤有点过敏怎么办
全身皮肤偏红怎么办
让蝎子蜇了怎么办
皮肤脏到发黑怎么办
脸上毛孔脏东西怎么办
花木兰遇见妲己怎么办?
狗皮肤溃烂化脓怎么办
剪短发头发少怎么办
神关羽武魂反贼怎么办
陆航飞行员停飞怎么办?
在陆航停飞怎么办?
大三陆航停飞怎么办?
江苏高考选修cc怎么办
2018年军产房怎么办
集团军被裁军长怎么办
被保留的村庄怎么办
武警军改新兵怎么办
凭证后附件太多怎么办
改革后军校学员怎么办
城管查的严怎么办
城管新制服协管怎么办
监察委事业编怎么办
露天烧烤城管不管怎么办?
怎么办用上海话怎么说
gta5直升机坏了怎么办
兵团改革非职工怎么办
美国开中餐签证怎么办
被网上喷子喷了怎么办
有护照去黎巴嫩怎么办
背包扣子坏了怎么办
酷狗m1电流声怎么办
x14头盔掉漆怎么办
摩托车头盔太紧怎么办