原题链接在这里:https://leetcode.com/problems/walls-and-gates/

题目:

You are given a m x n 2D grid initialized with these three possible values.

  1. -1 - A wall or an obstacle.
  2. 0 - A gate.
  3. INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than2147483647.

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

题解:

BFS, 先把所有gate加到que中。对于每一个从que中poll出来的gate,看四个方向是否有room, 若有,把room的值改正gate + 1, 在放回到que中.

Time Complexity: O(m*n). m = rooms.length, n = rooms[0].length. 每个点没有扫描超过两遍. Space: O(m*n).

AC Java:

 class Solution {
public void wallsAndGates(int[][] rooms) {
if(rooms == null || rooms.length == 0 || rooms[0].length == 0){
return;
} int m = rooms.length;
int n = rooms[0].length;
LinkedList<int []> que = new LinkedList<>();
int level = 1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(rooms[i][j] == 0){
que.add(new int[]{i, j});
}
}
} int [][] dirs = new int[][]{{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; while(!que.isEmpty()){
int size = que.size();
while(size-- > 0){
int [] cur = que.poll();
for(int [] dir : dirs){
int x = cur[0] + dir[0];
int y = cur[1] + dir[1];
if(x < 0 || x >= m || y < 0 || y >= n || rooms[x][y] != Integer.MAX_VALUE){
continue;
} que.add(new int[]{x, y});
rooms[x][y] = level;
}
} level++;
}
}
}

跟上Robot Room CleanerRotting OrangesShortest Distance from All Buildings.

最新文章

  1. 在CentOS下自动备份mysql
  2. loadrunner11.0 安装破解详解使用教程
  3. Leetcode-189 Rotate Array
  4. 记”Uri.IsWellFormedUriString”中的BUG
  5. WPF/Silverlight HierarchicalDataTemplate 模版的使用(转)
  6. Extjs 视频教程
  7. stm32上的Lava虚拟机开发进度汇报(2)
  8. SPRING IN ACTION 第4版笔记-第四章ASPECT-ORIENTED SPRING-011-注入AspectJ Aspect
  9. USB做Host的OTG原理
  10. iOS-设置状态栏白色以及覆盖状态栏
  11. 数据结构(RMQ):UVAoj 11235 Frequent values
  12. app开发历程——android手机显示服务器端图片思路
  13. python的行与缩进
  14. SQL中的delete和TRUNCATE的用法
  15. chapter5 函数
  16. HDU-1301 Jungle Roads(最小生成树[Prim])
  17. 第五章:Python基础の生成器、迭代器、序列化和虚拟环境的应用
  18. CTF--web 攻防世界web题 robots backup
  19. Chemical table CFR500 div2D(并查集)
  20. WIN 10下Mysql 5.7.21解压缩(免安装版)配置

热门文章

  1. Storm和JStorm(阿里的流处理框架)
  2. topcoder SRM 625 DIV2 IncrementingSequence
  3. ACM: HDU 5418 Victor and World - Floyd算法+dp状态压缩
  4. 【Oracle】悲观锁和乐观锁
  5. [IBM DB2] db2 terminate 和 db2 connect reset 有什么区别?
  6. Linux进程间通信:IPC对象——信号灯集详解
  7. linux查看memcached状态
  8. 使用RESTClient插件进行数据模拟(GET,POST)提交
  9. 使用swf与swc引入资源的区别[as3]
  10. [VBA] 打开文件夹