[LeetCode] Walls and Gates

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

没啥好说的,BFS。

 1 class Solution {
 2 public:
 3     void wallsAndGates(vector<vector<int>>& rooms) {
 4         if (rooms.empty() || rooms[0].empty()) return;
 5         int n = rooms.size(), m = rooms[0].size();
 6         queue<pair<int, int>> que;
 7         int cnt1 = 0, cnt2 = 0;
 8         for (int i = 0; i < n; ++i) {
 9             for (int j = 0; j < m; ++j) {
10                 if (rooms[i][j] == 0) {
11                     ++cnt1;
12                     que.push({i, j});
13                 }
14             }
15         }
16         const int dx[4] = {0, 1, 0, -1};
17         const int dy[4] = {1, 0, -1, 0};
18         while (!que.empty()) {
19             cnt2 = 0;
20             for (int i = 0; i < cnt1; ++i) {
21                 auto u = que.front();
22                 que.pop();
23                 int x = u.first, y = u.second;
24                 for (int j = 0; j < 4; ++j) {
25                     int xx = x + dx[j], yy = y + dy[j];
26                     if (xx >= 0 && xx < n && yy >= 0 && yy < m && rooms[xx][yy] > rooms[x][y]) {
27                         ++cnt2;
28                         rooms[xx][yy] = rooms[x][y] + 1;
29                         que.push({xx, yy});
30                     }
31                 }
32             }
33             cnt1 = cnt2;
34         }
35     }
36 };

 

posted @ 2015-09-25 13:02  Eason Liu  阅读(657)  评论(0编辑  收藏  举报