This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UnionFind | |
{ | |
public: | |
UnionFind(int n) | |
{ | |
parent = vector<int>(n, 0); | |
size = vector<int>(n, 1); | |
for (int i = 0; i < n; ++i) | |
parent[i] = i; | |
} | |
void connect(int i, int j) | |
{ | |
int rootI = root(i), rootJ = root(j); | |
if(rootI == rootJ)return; | |
if (size[rootI] <= size[rootJ]) | |
{ | |
parent[rootI] = rootJ; | |
size[rootJ] += size[rootI]; | |
} | |
else | |
{ | |
parent[rootJ] = rootI; | |
size[rootI] += size[rootJ]; | |
} | |
} | |
bool find(int i, int j) | |
{ | |
return root(i) == root(j); | |
} | |
int getSize(int i) | |
{ | |
int r = root(i); | |
return size[r]; | |
} | |
private: | |
vector<int> parent, size; | |
int root(int i) | |
{ | |
if (i == parent[i])return i; | |
int r = root(parent[i]); | |
parent[i] = r; | |
return r; | |
} | |
}; | |
class Solution { | |
public: | |
vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) { | |
int n = grid.size(), m = n ? grid[0].size() : 0, len = hits.size(); | |
pair<int, int> dirs[4] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1} }; | |
//we erase bricks first, then add them in reverse order and check connectivity | |
for (auto& hit : hits) | |
{ | |
if(!grid[hit[0]][hit[1]]) | |
{ | |
hit[0] = -1; | |
hit[1] = -1; | |
continue; | |
} | |
grid[hit[0]][hit[1]] = 0; | |
} | |
UnionFind uf(n * m + 1); | |
for (int i = 0; i < n; ++i) | |
{ | |
for (int j = 0; j < m; ++j) | |
{ | |
if (grid[i][j]) | |
{ | |
int idx = i * m + j + 1; | |
if (!i)uf.connect(0, idx); | |
for (auto& dir : dirs) | |
{ | |
int x = i + dir.first, y = j + dir.second; | |
if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y]) | |
uf.connect(idx, x * m + y + 1); | |
} | |
} | |
} | |
} | |
vector<int> res; | |
stack<int> st; | |
int currSize = uf.getSize(0); | |
for(int k = len - 1; k >= 0; --k) | |
{ | |
int i = hits[k][0], j = hits[k][1]; | |
if(i == -1 || j == -1) | |
{ | |
st.push(0); | |
continue; | |
} | |
grid[i][j] = 1; | |
if(!i)uf.connect(0, i * m + j + 1); | |
for (auto& dir : dirs) | |
{ | |
int x = i + dir.first, y = j + dir.second; | |
if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y]) | |
uf.connect(i * m + j + 1, x * m + y + 1); | |
} | |
st.push(uf.getSize(0) - currSize? uf.getSize(0) - currSize - 1: 0); | |
currSize = uf.getSize(0); | |
} | |
while(st.size()) | |
{ | |
res.push_back(st.top()); | |
st.pop(); | |
} | |
return res; | |
} | |
}; |
No comments:
Post a Comment