forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swim-in-rising-water.cpp
59 lines (54 loc) · 1.74 KB
/
swim-in-rising-water.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
// Time: O(n^2)
// Space: O(n^2)
class Solution {
public:
int swimInWater(vector<vector<int>>& grid) {
const int n = grid.size();
vector<pair<int, int>> positions(n * n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
positions[grid[i][j]] = {i, j};
}
}
static const vector<pair<int, int>> directions{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
UnionFind union_find(n * n);
for (int elevation = 0; elevation < positions.size(); ++elevation) {
int i, j;
tie(i, j) = positions[elevation];
for (const auto& dir : directions) {
int x = i + dir.first;
int y = j + dir.second;
if (0 <= x && x < n &&
0 <= y && y < n &&
grid[x][y] <= elevation) {
union_find.union_set(i * n + j, x * n + y);
if (union_find.find_set(0) == union_find.find_set(n * n - 1)) {
return elevation;
}
}
}
}
return n * n - 1;
}
private:
class UnionFind {
public:
UnionFind(const int n) : set_(n) {
iota(set_.begin(), set_.end(), 0);
}
int find_set(const int x) {
if (set_[x] != x) {
set_[x] = find_set(set_[x]); // Path compression.
}
return set_[x];
}
void union_set(const int x, const int y) {
int x_root = find_set(x), y_root = find_set(y);
if (x_root != y_root) {
set_[min(x_root, y_root)] = max(x_root, y_root);
}
}
private:
vector<int> set_;
};
};