Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
swim-in-rising-water.cpp 1.74 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2018-02-08 22:45 +08:00 . Update swim-in-rising-water.cpp
// 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_;
};
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助