摘要:题目解答每一次加入进来的结点,都时当前位置可到达的最短距离。
题目:
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 = 2147483647 to represent INF as 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
解答:
每一次加入进来的结点,都时当前位置gate可到达的最短距离。用BFS逐层扫。
public void wallsAndGates(int[][] rooms) { if (rooms == null || rooms.length == 0 || rooms[0].length == 0) return; Queueq = new LinkedList<>(); int m = rooms.length, n = rooms[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (rooms[i][j] == 0) { q.add(new int[]{i, j}); } } } int[][] dir = {{-1, 0},{1, 0},{0, 1},{0, -1}}; while (!q.isEmpty()) { int[] curt = q.poll(); int i = curt[0], j = curt[1]; for (int k = 0; k < dir.length; k++) { int x = i + dir[k][0], y = j + dir[k][1]; if (x < 0 || x > m - 1 || y < 0 || y > n - 1 || rooms[x][y] != Integer.MAX_VALUE) { continue; } rooms[x][y] = rooms[i][j] + 1; q.add(new int[] {x, y}); } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/64915.html
摘要:广度优先搜索复杂度时间空间思路实际上就是找每个房间到最近的门的距离,我们从每个门开始,广度优先搜索并记录层数就行了。这题要注意剪枝,如果下一步是门或者下一步是墙或者下一步已经访问过了,就不要加入队列中。 Walls and Gates You are given a m x n 2D grid initialized with these three possible values....
摘要:题目链接这道题感觉是那道的简化版,思路都是一样的。是把所有的点都先放到里面,然后一起遍历。这种写法的好处是保证了每个点都只被放进一次,不会重复遍历。保证了时间复杂是。可以不写成层次遍历的形式,直接,的程序 Walls and Gates 题目链接:https://leetcode.com/problems... 这道题感觉是那道Shortest Distance from All Bu...
Problem There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it wont stop rolling until hitting a wall. When the ball sto...
摘要:本人邮箱欢迎转载转载请注明网址代码已经全部托管有需要的同学自行下载引言迷宫对于大家都不会陌生那么迷宫是怎么生成已经迷宫要如何找到正确的路径呢用代码又怎么实现带着这些问题我们继续往下看并查集朋友圈有一种算法就做并查集什么意思呢比如现在有零 本人邮箱: 欢迎转载,转载请注明网址 http://blog.csdn.net/tianshi_kcogithub: https://github.c...
摘要:简述与同为数据库但是为数据库而为文档型数据库存储的是文档的二进制化内部执行引擎为解释器把文档存储成结构在查询时转换为对象并可以通过熟悉的语法来操作的安装启动在上直接下载解压运行即可本身是已编译好的二进制可执行文件如果报错说明你的服务器和 简述 mongoDB与redis同为noSql数据库,但是redis为kv数据库(key/value),而mongoDB为文档型数据库存储的是文档(B...
阅读 2818·2021-11-25 09:43
阅读 2441·2021-10-09 09:44
阅读 2781·2021-09-22 15:49
阅读 2523·2021-09-01 11:43
阅读 2528·2019-08-30 14:16
阅读 437·2019-08-29 17:24
阅读 3009·2019-08-29 14:00
阅读 1365·2019-08-29 13:05