778. 水位上升的泳池中游泳
分类:并查集、二分答案、最短路
并查集思路挺简单的。由小到大挨个加,检查下连上了没就行。
class UnionFind{
private:
vector<int> u;
vector<int> sz;
public:
int member;
UnionFind(int n):member(n), u(n), sz(n, 1){
iota(u.begin(), u.end(), 0);
}
int root(int i){
return u[i] == i ? i : u[i] = root(u[i]);
}
bool connect(int i, int j){
int ri = root(i), rj = root(j);
if(ri == rj){
return false;
}
if(sz[ri] < sz[rj]){
swap(ri, rj);
}
u[rj] = ri;
sz[ri] += sz[rj];
member--;
return true;
}
bool isConnected(int i, int j){
return root(i) == root(j);
}
};
class Solution {
public:
struct edge{
int i, j, v;
edge(int i, int j, int v):i(i), j(j), v(v){}
bool operator < (const edge & other) const {
return v > other.v;
}
};
int d[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int swimInWater(vector<vector<int>>& grid) {
int n = grid.size();
priority_queue<edge> q;
for(int i=0; i<n; i++){
for(int j=0; j<n; j++){
q.push(edge(i, j, grid[i][j]));
}
}
UnionFind u(n*n);
while(!q.empty()){
edge cur = q.top(); q.pop();
for(int i=0; i<4; i++){
int x = cur.i + d[i][0], y = cur.j + d[i][1];
if(x>-1 && y>-1 && x<n && y<n && grid[x][y]<cur.v){
u.connect(x*n+y, cur.i*n+cur.j);
}
if(u.isConnected(0, n*n-1)) return cur.v;
}
}
return n*n-1;
}
};
二分答案和最短路思路同昨天的题,摸了
2021/01/30