LeetCode Walls and Gates

原题链接在这里: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:

 1 public class Solution {
 2     public void wallsAndGates(int[][] rooms) {
 3         if(rooms == null || rooms.length == 0 || rooms[0].length == 0){
 4             return;
 5         }
 6         int [][] fourDire = {{0,1},{0,-1},{1,0},{-1,0}};
 7         LinkedList<int []> que = new LinkedList<int []>();
 8         
 9         for(int i = 0; i<rooms.length; i++){
10             for(int j = 0; j<rooms[0].length; j++){
11                 if(rooms[i][j] == 0){
12                     que.add(new int[]{i,j});
13                 }
14             }
15         }
16         
17         while(!que.isEmpty()){
18             int [] gate = que.poll();
19             int x = gate[0];
20             int y = gate[1];
21             for(int k = 0; k<4; k++){
22                 int newX = x + fourDire[k][0];
23                 int newY = y + fourDire[k][1];
24                 if(newX>=0 && newX<rooms.length && newY>=0 && newY<rooms[0].length){
25                     if(rooms[newX][newY] == Integer.MAX_VALUE){
26                         rooms[newX][newY] = rooms[x][y] + 1;
27                         que.add(new int[]{newX, newY});
28                     }
29                 }
30             }
31         }
32     }
33 }

 

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/5226225.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值