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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| class Solution { vector<vector<int>> afterGrid; vector<vector<pair<int, int>>> uf; vector<vector<int>> setNum; int row, col; vector<pair<int, int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public: vector<int> hitBricks(vector<vector<int>>& grid, vector<vector<int>>& hits) { row = grid.size(); col = grid[0].size(); init (grid, hits);
vector<int> ans; for (int i = hits.size() - 1; i >= 0; i--) { int x = hits[i][0], y = hits[i][1]; if (!grid[x][y]) { ans.push_back(0); continue; } afterGrid[x][y] = 1; auto p1 = make_pair(x, y); int cnt = 0;
uf[x][y] = make_pair(x, y); setNum[x][y] = 1;
for (auto &k : directions) { auto p2 = make_pair(x + k.first, y + k.second); if (!valid(p2) || afterGrid[p2.first][p2.second] == 0) continue; auto h2 = head(p2); auto h1 = head(p1); if (h1 == h2) { continue; } if (h2.first != 0) { cnt += setNum[h2.first][h2.second]; } merge(p1, p2); } auto h = head(p1); if (h.first != 0) { ans.push_back(0); } else { ans.push_back(cnt); } } reverse(ans.begin(), ans.end()); return ans; }
void init (vector<vector<int>>& grid, vector<vector<int>>& hits) { afterGrid = grid; for (auto &hit : hits) { afterGrid[hit[0]][hit[1]] = 0; }
uf = vector<vector<pair<int,int>>>(row, vector<pair<int, int>>(col, {0, 0})); setNum.assign(row, vector<int>(col, 0)); for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (!afterGrid[i][j]) continue; uf[i][j] = make_pair(i, j); setNum[i][j] = 1; } }
for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (!afterGrid[i][j]) continue; auto p1 = make_pair(i, j); for (auto &k : directions) { auto p2 = make_pair(i + k.first, j + k.second); if (!valid(p2) || afterGrid[p2.first][p2.second] == 0) continue; merge(p1, p2); } } } }
bool valid(pair<int, int> &p) { return p.first >= 0 && p.first < row && p.second >= 0 && p.second < col; }
pair<int, int> head(pair<int, int> p) { while (uf[p.first][p.second] != p) { p = uf[p.first][p.second]; } return p; }
void merge (pair<int, int> a, pair<int, int> b) { auto h1 = head(a), h2 = head(b); if (h1 == h2) return; if (h1.first == 0) { uf[h2.first][h2.second] = h1; setNum[h1.first][h1.second] += setNum[h2.first][h2.second]; setNum[h2.first][h2.second] = 0; } else { uf[h1.first][h1.second] = h2; setNum[h2.first][h2.second] += setNum[h1.first][h1.second]; setNum[h1.first][h1.second] = 0; } } };
|