-
Notifications
You must be signed in to change notification settings - Fork 0
/
287.walls-and-gates.cpp
84 lines (82 loc) · 1.6 KB
/
287.walls-and-gates.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <vector>
#include <queue>
#include <set>
#include <iostream>
#include <utility>
using namespace std;
class Solution
{
public:
void wallsAndGates(vector<vector<int>> &rooms)
{
queue<pair<int,int>> q_room;
set<pair<int,int>> filled;
int step = 0;
int height = rooms.size();
int width;
if (height > 0)
width = rooms[0].size();
for(int i = 0; i != height; i++)
{
for(int j = 0; j != width; j++)
{
if(rooms[i][j] == 0)
{
q_room.push(pair(i,j));
filled.insert(pair(i,j));
}
}
}
while (!q_room.empty())
{
for (int i = 0, e = q_room.size(); i != e; i++)
{
auto p = q_room.front();
if (rooms[p.first][p.second] != -1)
{
fillAdjacentRoom(p, q_room, filled, width, height);
rooms[p.first][p.second] = step;
}
q_room.pop();
}
step++;
};
}
void fillAdjacentRoom(pair<int, int> p,
queue<pair<int, int>> &q_room,
set<pair<int,int>> &filled, int width, int height)
{
if (p.first - 1 >= 0)
{
p.first--;
fillOnlyNewRoom(p, q_room, filled);
p.first++;
}
if (p.first + 1 < height)
{
p.first++;
fillOnlyNewRoom(p, q_room, filled);
p.first--;
}
if (p.second - 1 >= 0)
{
p.second--;
fillOnlyNewRoom(p, q_room, filled);
p.second++;
}
if (p.second + 1 < width)
{
p.second++;
fillOnlyNewRoom(p, q_room, filled);
p.second--;
}
}
void fillOnlyNewRoom(pair<int, int> p, queue<pair<int, int>> &q_room, set<pair<int,int>> &filled)
{
if (filled.find(p) == filled.end())
{
q_room.push(p);
filled.insert(p);
}
}
};