286. Walls and Gates
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 value2 31 - 1 = 2147483647
to representINF
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
广度优先, 如果有多个起点谁先抢到某个点, 就标记上到该起点的距离, 所以距离是较小的那一个值
#include <iostream> #include <vector> #include <queue> using namespace std; class Solution { private: const int dir[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; int m, n; const int GATE = 0; const int EMPTY = INT_MAX; const int WALL = -1; public: void wallsAndGates(vector<vector<int> >& rooms) { m = rooms.size(); if(m == 0) return ; n = rooms.size(); bfs(rooms); return ; } private: void bfs(vector<vector<int> >& rooms) { queue<pair<pair<int, int>, int> > q; for(int i = 0; i < m; ++ i) { for(int j = 0; j < n; ++ j) { if(rooms[i][j] == GATE) { q.push(make_pair(make_pair(i, j), 0)); } } } vector<vector<bool> > visited(m, vector<bool>(n, false)); while(!q.empty()) { int curx = q.front().first.first; int cury = q.front().first.second; int step = q.front().second; q.pop(); rooms[curx][cury] = step; for(int i = 0; i < 4; ++ i) { int newX = curx + dir[i][0]; int newY = cury + dir[i][1]; if(inArea(newX, newY) && !visited[newX][newY] && rooms[newX][newY] == EMPTY) { visited[newX][newY] = true; rooms[newX][newY] = step + 1; q.push(make_pair(make_pair(newX, newY), step + 1)); } } } } bool inArea(int x, int y) { return x >= 0 && x < m && y >= 0 && y < n; } }; /* INF -1 0 INF INF INF INF -1 INF -1 INF -1 0 -1 INF INF 3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4 */