Walls and Gates 解答
2015-11-08 04:38
288 查看
Question
You are given a m x n 2D grid initialized with these three possible values.-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
After running your function, the 2D grid should be:
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
Solution
Problems like "shortest distance/ nearest neighbor" can be always solved by BFS.distance from a specific point (x, y) to one exit (x', y') = distance from (x', y') to (x, y)
So we start BFS on exit points.
Af first, I tried BFS on every exit point one by one, but the time consuming is huge and reports "Time Limit Exceed".
One key point is that we can add all exit points at first, and do BFS once. Time complexity O(mn).
For BFS, don't forget visited[][] array.
public class Solution { private final int[][] directions = {{0,1},{0,-1},{1,0},{-1,0}}; public void wallsAndGates(int[][] rooms) { if (rooms == null || rooms.length < 1) { return; } int m = rooms.length, n = rooms[0].length; int distance = 0; Deque<int[]> queue = new LinkedList<int[]>(); boolean[][] visited = new boolean[m] ; // Add all exit points to queue for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (rooms[i][j] == 0) { queue.add(new int[]{i, j}); } } } // BFS while (!queue.isEmpty()) { distance++; int size = queue.size(); for (int i = 0; i < size; i++) { int[] prev = queue.poll(); for (int k = 0; k < 4; k++) { int newX = prev[0] + directions[k][0]; int newY = prev[1] + directions[k][1]; if (newX < 0 || newX >= rooms.length || newY < 0 || newY >= rooms[0].length) { continue; } if (rooms[newX][newY] == -1) { continue; } // !!! check visisted if (visited[newX][newY]) { continue; } visited[newX][newY] = true; if (rooms[newX][newY] > distance) { rooms[newX][newY] = distance; } queue.offer(new int[]{newX, newY}); } } } } }
相关文章推荐
- 【LeetCode】Binary Tree Zigzag Level Order Traversal
- [Python爬虫] scrapy爬虫系列 <一>.安装及入门介绍
- Mysql学习篇之---Windows环境下安装
- C++: 拷贝管理
- Integer自动装箱分析
- 匿名内部类构造函数分析
- PHP时间戳、时间戳转北京时间日期
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]
- [并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]
- 静态内部类和非静态内部类的区别
- 编译时、运行时、构建时(一)
- 编译时、运行时、构建时(二)
- Smallest Rectangle Enclosing Black Pixels 解答
- c++ 11 数组 和lambda表达式 语法 / 函数包装器 基本用法
- 深入理解Java中的final关键字
- 35 个 Java 代码性能优化总结
- 从JAVA多线程理解到集群分布式和网络设计的浅析
- Azure Reserved IP
- #soj 3076 相同字符串(tire树)
- Azure Remote Desktop: "An error occurred while loading from file *.rdp"