542. 01 Matrix
来源:互联网 发布:unity3d招聘 编辑:程序博客网 时间:2024/05/16 20:25
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 0
Example 2:
Input:
0 0 00 1 01 1 1Output:
0 0 00 1 01 2 1
Note:
- 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错不了,但是一个个点做的话会TLE,想想也是,不同的节点的BFS有一定的重叠,其实完全可以一起BFS遍历啊!
还有值得注意的一点是,给的输入是List,一般都是int[],所以这里就直接用输入,
package l542;import java.util.LinkedList;import java.util.List;import java.util.Queue;/* * do bfs at same time * 直接在输入的list对象上更改就好了 */public class Solution { public List<List<Integer>> updateMatrix(List<List<Integer>> matrix) { Queue<int[]> q = new LinkedList<int[]>(); for(int i=0; i<matrix.size(); i++) { for(int j=0; j<matrix.get(0).size(); j++) { if(matrix.get(i).get(j) == 0) { q.add(new int[]{i, j}); } else { matrix.get(i).set(j, -1);//用来标识是否找到了该点的最短值 } } } while(!q.isEmpty()) { int[] cell = q.remove(); int x = cell[0], y = cell[1];int step = matrix.get(x).get(y); if(x > 0 && matrix.get(x-1).get(y) == -1){q.add(new int[]{x-1, y});matrix.get(x-1).set(y, step+1);}if(y > 0 && matrix.get(x).get(y-1) == -1) {q.add(new int[]{x, y-1});matrix.get(x).set(y-1, step+1);}if(x < matrix.size()-1 && matrix.get(x+1).get(y) == -1){q.add(new int[]{x+1, y});matrix.get(x+1).set(y, step+1);}if(y < matrix.get(0).size()-1 && matrix.get(x).get(y+1) == -1){q.add(new int[]{x, y+1});matrix.get(x).set(y+1, step+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
- hystrix 集群监控 turbine 及aop 开发hystrix
- 前端知识教程链接
- 字符串反转方法2(调用接口函数)
- matleb对图像压缩的处理
- 规则分幅裁剪和不规则分幅裁剪
- 542. 01 Matrix
- 宿迁铁通强化固定资产管理
- java中多线程的一些知识
- 3分钟了解Manjaro Linux
- checkBox全选
- mac 下安装swoole
- liux初学者周周感悟--静态库和动态库
- Android 实现监听应用从后台回到前台
- 配置mysql查询缓存