voidunionSet(int p, int q) { int rootP = find(p); int rootQ = find(q); if (rootP == rootQ) return;
if (size[rootP] > size[rootQ]) { parent[rootQ] = rootP; size[rootP] += size[rootQ]; } else { parent[rootP] = rootQ; size[rootQ] += size[rootP]; } count--; } // 判斷p q 是否互相連通 boolconnected(int p, int q) { int rootP = find(p); int rootQ = find(q); return rootQ == rootP; } // 返回 節點 x 的根節點 intfind(int x) { while (parent[x] != x) { // 進行路徑壓縮 parent[x] = parent[parent[x]]; x = parent[x]; } return x; } intlength() { return count; } }; classSolution { public: voidsolve(vector<vector<char>>& board){ int m = board.size(), n = board[0].size();
UF *uf = newUF(m * n + 1); int dummy = m * n; // 首行與末行的O與dummy 連通 for (int i = 0; i < m; ++i) { if (board[i][0] == 'O') uf->unionSet(i * n, dummy); if (board[i][n - 1] == 'O') uf->unionSet(i * n + n - 1, dummy); }
vector<vector<int> > action = {{1, 0}, {0, 1}, {0, -1}, {-1, 0}}; for (int i = 1; i < m - 1; ++i) { for (int j = 1; j < n - 1; ++j) { if (board[i][j] == 'O') { // 将此 O 与上下左右的 O 连通 for (int k = 0; k < 4; ++k) { int x = i + action[k][0]; int y = j + action[k][1]; if (board[x][y] == 'O') uf->unionSet(x * n + y, i * n + j); } } } } // 所有不和 dummy 连通的 O,都要被替换 for (int i = 1; i < m - 1; i++) { for (int j = 1; j < n - 1; j++) { if (!uf->connected(dummy, i * n + j)) board[i][j] = 'X'; } } } };