标签:
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
思路:BSF。
1 class Solution { 2 public: 3 void wallsAndGates(vector<vector<int>>& rooms) { 4 const int inf = INT_MAX; 5 queue<pair<int, int> > q; 6 int height = rooms.size(); 7 int width = height > 0 ? rooms[0].size() : 0; 8 for (int i = 0; i < height; i++) 9 for (int j = 0; j < width; j++) 10 if (rooms[i][j] == 0) q.push(make_pair(i, j)); 11 int rowChange[] = {0, -1, 0, 1}; 12 int colChange[] = {1, 0, -1, 0}; 13 while (!q.empty()) { 14 pair<int, int> cur = q.front(); 15 q.pop(); 16 int row = get<0>(cur), col = get<1>(cur); 17 for (int i = 0; i < 4; i++) { 18 int nextRow = row + rowChange[i]; 19 int nextCol = col + colChange[i]; 20 if (nextRow > -1 && nextRow < height && 21 nextCol > -1 && nextCol < width && rooms[nextRow][nextCol] == inf) { 22 rooms[nextRow][nextCol] = rooms[row][col] + 1; 23 q.push(make_pair(nextRow, nextCol)); 24 } 25 } 26 } 27 } 28 };
标签:
原文地址:http://www.cnblogs.com/fenshen371/p/5798462.html