LeetCode Walls and Gates

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 }

 

以上是关于LeetCode Walls and Gates的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 286: Walls and Gates

[LeetCode] 286. Walls and Gates 墙和门

[Locked] Walls and Gates

286 Walls and Gates

Walls and Gates

286. Walls and Gates