286. Walls and Gates
2016-03-14 05:22
302 查看
You are given a m x n 2D grid initialized with these three possible values.
After running your function, the 2D grid should be:
-1- A wall or an obstacle.
0- A gate.
INF- Infinity means an empty room. We use the value
231 - 1 = 2147483647to represent
INFas you may assume that the distance to a gate is less than
2147483647.Fill each empty room with the distance to its nearest gate. If it is impossible to reach a gate, it should be filled with
INF.For example, given the 2D grid:
INF | -1 | 0 | INF |
INF | INF | INF | -1 |
INF | -1 | INF | -1 |
0 | -1 | INF | INF |
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4Similar:130. Surrounded Regions200. Number of Islands317. Shortest Distance from All Buildings
public class Solution { public void wallsAndGates(int[][] rooms) { if (rooms.length == 0 || rooms[0].length==0) return; Queue<int[]> queue = new LinkedList<int[]>(); int m = rooms.length; int n = rooms[0].length; int[] shift = {1, 0, -1, 0, 1}; for (int i=0; i<m; i++) for (int j=0; j<n; j++) { if (rooms[i][j] == 0) { queue.offer(new int[] {i,j}); } } int level = 1; while (!queue.isEmpty()) { int size = queue.size(); while (size > 0) { int[] pt = queue.poll(); // rooms[pt[0]][pt[1]] = level; for (int k = 0; k < 4; k++) { int r = pt[0] + shift[k]; int c = pt[1] + shift[k+1]; if (r>=0 && r<m && c>=0 && c<n && rooms[r][c] == Integer.MAX_VALUE) { rooms[r][c] = level; // set here in case point [1][1] would put [1][0] in the queue Twice queue.offer(new int[] {r,c}); } } size--; } level++; } return; } }
相关文章推荐
- 317. Shortest Distance from All Buildings
- 105. Construct Binary Tree from Preorder and Inorder Traversal
- 反思与回顾
- C++ Exceptional 最小化编译期依赖
- Leetcode 3. Longest Substring Without Repeating Characters
- vivo
- Omnispace 收藏夹
- 单例模式的常见高效实践
- System and device programming——thread and semaphore implements
- APK加壳【3】通用内存加载dex方案分析
- APK加壳【2】内存加载dex实现详解
- APK加壳【1】初步方案实现详解
- CUDA 7.0 速查手册
- dex注入实现详解
- cs231n assignment1 tips
- HDU 5047 Sawtooth 高精度
- 恒生电子
- OpenGL with PyOpenGL tutorial Python and PyGame p.1 - Making a rotating Cube Example
- 纯css3实现斑马线repeating-linear-gradient和linear-gradient的妙用
- Reorder Linked List