-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathregionsCutBySlashes.cpp
More file actions
66 lines (60 loc) · 1.66 KB
/
regionsCutBySlashes.cpp
File metadata and controls
66 lines (60 loc) · 1.66 KB
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
// Source: https://leetcode.com/problems/regions-cut-by-slashes/
// Author: Miao Zhang
// Date: 2021-03-29
class DSU {
public:
DSU(int n): root_(n) {
for (int i = 0; i < n; i++) {
root_[i] = i;
}
}
int find(int x) {
if (root_[x] != x) root_[x] = find(root_[x]);
return root_[x];
}
void merge(int x, int y) {
root_[find(x)] = find(y);
}
private:
vector<int> root_;
};
/***************************************************
* \ 0 /
* 3 1
* / 2 \
*
***************************************************/
class Solution {
public:
int regionsBySlashes(vector<string>& grid) {
int n = grid.size();
DSU dsu(4 * n * n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int idx = 4 * (i * n + j);
if (grid[i][j] == '/') {
dsu.merge(idx + 0, idx + 3);
dsu.merge(idx + 1, idx + 2);
} else if (grid[i][j] == '\\') {
dsu.merge(idx + 0, idx + 1);
dsu.merge(idx + 2, idx + 3);
} else {
dsu.merge(idx + 0, idx + 1);
dsu.merge(idx + 1, idx + 2);
dsu.merge(idx + 2, idx + 3);
}
if (i + 1 < n) {
dsu.merge(idx + 2, idx + 4 * n + 0);
}
if (j + 1 < n) {
dsu.merge(idx + 1, idx + 4 + 3);
}
}
}
int res = 0;
for (int i = 0; i < 4 * n * n; i++) {
if (dsu.find(i) == i) res++;
}
return res;
}
};