[LeetCode]542. 01 Matrix
来源:互联网 发布:淘宝十字绣代绣可靠吗 编辑:程序博客网 时间:2024/06/06 12:47
https://leetcode.com/problems/01-matrix/#/description
给一个二维01数组,找出每个位置和最近的0的距离
BFS
先把所有0入队,把1置为MAX_VALUE,然后把最靠近0的1的距离算出来,然后将他们入队,再算距离最靠近0的1的1的距离算出来,依次处理
public class Solution { public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) { int m = matrix.size(); int n = matrix.get(0).size(); Queue<int[]> queue = new LinkedList<>(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix.get(i).get(j) == 0) { queue.offer(new int[] {i, j}); } else { matrix.get(i).set(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.get(r).get(c) <= matrix.get(cell[0]).get(cell[1]) + 1) continue; queue.add(new int[] {r, c}); matrix.get(r).set(c, matrix.get(cell[0]).get(cell[1]) + 1); } } return matrix; }}
0 0
- Leetcode-542. 01 Matrix
- [LeetCode]542. 01 Matrix
- leetcode 542. 01 Matrix
- [leetcode]542. 01 Matrix
- 【LeetCode】542. 01 Matrix
- 542. 01 Matrix [LeetCode]
- [LeetCode] 542. 01 Matrix
- leetcode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- LeetCode 542. 01 Matrix
- 【leetcode】542. 01 Matrix的解法总结
- [Leetcode] 542. 01 Matrix 解题报告
- leetcode-542-01 Matrix
- [LeetCode.542]01 Matrix
- LeetCode之01 Matrix
- LeetCode--01 Matrix
- 【LeetCode】01 Matrix 解题报告
- [Leetcode] #542 01 Matrix (BFS)
- android权限相关整理
- linux磁盘的两种分区方法
- Java中的包裹类型以及包裹类型Character的几个用法
- 【计算机网络原理】第四章 数据链路层
- Oracle 显示游标小结
- [LeetCode]542. 01 Matrix
- Js数组去除空值
- UML简单入门
- 分别用函数和带参的宏,从三个数中找出最大的数。
- 面对对象编程的优势之一
- 大话设计模式-----(四)迪米特法则、外观模式、建造者模式
- maven上传jar包-命令行
- spring配置特殊错误处理
- Git