Leetcode 286: 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 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
 1 public class Solution {
 2     public void WallsAndGates(int[,] rooms) {
 3         if (rooms == null) return;
 4         
 5         int rows = rooms.GetLength(0), cols = rooms.GetLength(1); 
 6         
 7         if (rows == 0 || cols == 0) return;
 8         
 9         var dirs = new int[,] {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
10         var queue = new Queue<Tuple<int, int>>();
11         
12         for (int i = 0; i < rows; i++)
13         {
14             for (int j = 0; j < cols; j++)
15             {
16                 if (rooms[i, j] == 0)
17                 {
18                     queue.Enqueue(new Tuple<int, int>(i, j));
19                 }
20             }    
21         }
22         
23         int count = queue.Count, distances = 0;
24         while (queue.Count > 0)
25         {
26             while (count-- > 0)
27             {
28                 var node = queue.Dequeue();
29                 
30                 if (rooms[node.Item1, node.Item2] == Int32.MaxValue)
31                 {
32                     rooms[node.Item1, node.Item2] = distances;
33                 }
34                 
35                 for (int i = 0; i < 4; i++)
36                 {
37                     var ni = node.Item1 + dirs[i, 0];
38                     var nj = node.Item2 + dirs[i, 1];
39                     
40                     if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && rooms[ni, nj] == Int32.MaxValue)
41                     {
42                         queue.Enqueue(new Tuple<int, int>(ni, nj));
43                     }
44                 }
45             }
46             
47             count = queue.Count;
48             distances++;
49         }
50     }
51 }

 

posted @ 2018-01-29 06:27  逸朵  阅读(143)  评论(0)    收藏  举报