-
Notifications
You must be signed in to change notification settings - Fork 3
/
959.cpp
84 lines (82 loc) · 2.84 KB
/
959.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
class DisjointSet {
private:
vector<int> parent;
vector<int> rank;
int remain;
public:
DisjointSet(int size) {
parent.resize(size, 0);
rank.resize(size, 0);
remain = size;
for (int i = 0; i < size; ++i) parent[i] = i;
}
int find(int x) {
if (x != parent[x]) {
parent[x] = find(parent[x]);
}
return parent[x];
}
void join(int x, int y) {
int parentX = find(x);
int parentY = find(y);
if (parentX == parentY) return;
remain--;
if (rank[parentX] > rank[parentY]) {
parent[parentY] = parentX;
}
else if (rank[parentX] < rank[parentY]) {
parent[parentX] = parentY;
}
else {
parent[parentY] = parentX;
rank[parentX]++;
}
}
int getRemain() {
return remain;
}
};
class Solution {
public:
int regionsBySlashes(vector<string>& grid) {
int n = grid.size();
DisjointSet* disjointSet = new DisjointSet(n * n * 4);
int rowExpand = n * 4;
// 0 up; 1 right; 2 down; 3 left
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (grid[i][j] == ' ') {
disjointSet->join(i * rowExpand + j * 4 + 0, i * rowExpand + j * 4 + 1);
disjointSet->join(i * rowExpand + j * 4 + 1, i * rowExpand + j * 4 + 2);
disjointSet->join(i * rowExpand + j * 4 + 2, i * rowExpand + j * 4 + 3);
disjointSet->join(i * rowExpand + j * 4 + 0, i * rowExpand + j * 4 + 3);
}
else if (grid[i][j] == '/') {
disjointSet->join(i * rowExpand + j * 4 + 0, i * rowExpand + j * 4 + 3);
disjointSet->join(i * rowExpand + j * 4 + 1, i * rowExpand + j * 4 + 2);
}
else {
disjointSet->join(i * rowExpand + j * 4 + 0, i * rowExpand + j * 4 + 1);
disjointSet->join(i * rowExpand + j * 4 + 2, i * rowExpand + j * 4 + 3);
}
// up
if (i > 0) {
disjointSet->join(i * rowExpand + j * 4 + 0, (i - 1) * rowExpand + j * 4 + 2);
}
// down
if (i < n - 1) {
disjointSet->join(i * rowExpand + j * 4 + 2, (i + 1) * rowExpand + j * 4 + 0);
}
// left
if (j > 0) {
disjointSet->join(i * rowExpand + j * 4 + 3, i * rowExpand + (j - 1) * 4 + 1);
}
// right
if (j < n - 1) {
disjointSet->join(i * rowExpand + j * 4 + 1, i * rowExpand + (j + 1) * 4 + 3);
}
}
}
return disjointSet->getRemain();
}
};