根据题目中的被‘X’围绕的‘O’可知:1)位于边界上的‘O’不会被填充;2)凡是不与边界上的‘O’相连的其他“O”都会被填充。
所以如果用并查集的思想来解决这一道题的话,需要先找出边界上的’O‘,用虚拟节点作为父节点。并且把相邻的’O‘进行一个路径压缩,
//把四周的 O 都和一个虚拟结点合并起来;
//在内部,只看两个方向,把 O 都合并起来;
//最后再扫一次数组,不和「虚拟结点」连接的 O 都标记成 X。
class Solution {
public void solve(char[][] board) {
int rows = board.length;
if (rows == 0)
return;
int cols = board[0].length;
if (cols == 0) {
return;
}
//每一个节点都有父节点,多余的一个位置用于存放虚拟节点
UnionFind unionFind = new UnionFind(rows * cols + 1);
int dummyNode = rows * cols;
//处理第一行和最后一行,将其中的’O'与虚拟节点相连接
for (int j = 0; j < cols; j++) {
if (board[0][j] == 'O') {
unionFind.union(getIndex(0, j, cols), dummyNode);
}
if (board[rows-1][j] == 'O') {
unionFind.union(getIndex(rows - 1, j, cols), dummyNode);
}
}
//处理左右两行,将这里的‘O'与虚拟节点相连接
for (int i = 1; i < rows - 1; i++) {
if (board[i][0] == 'O') {
unionFind.union(getIndex(i, 0, cols), dummyNode);
}
if (board[i][cols - 1] == 'O') {
unionFind.union(getIndex(i, cols - 1, cols), dummyNode);
}
}
//合并相邻的’O',只从两个方向其实就可以做到不重不漏了。
int [][] directions = new int[][]{{0, 1}, {1, 0}};
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'O') {
for (int[] direction : directions) {
int newX = i + direction[0];
int newY = j + direction[1];
if (newX < rows && newY < cols && board[newX][newY] == 'O') {
unionFind.union(getIndex(i, j, cols), getIndex(newX, newY, cols));
}
}
}
}
}
//判断是否和虚拟节点相连,不需要检查边缘的‘o’
for (int i = 1; i < rows-1; i++) {
for (int j = 1; j < cols-1; j++) {
if (board[i][j] == 'O') {
if (!unionFind.isConnected(getIndex(i, j, cols), dummyNode)) {
board[i][j] = 'X';
}
}
}
}
}
private int getIndex(int x, int y, int cols) {
return x * cols + y;
}
}
class UnionFind {
private int[] parent;
public UnionFind(int n) {
this.parent = new int[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
}
}
public boolean isConnected(int x, int y) {
return find(x) == find(y);
}
public int find(int x) {
while (x != parent[x]) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
public void union(int x, int y) {
int xRoot = find(x);
int yRoot = find(y);
//隶属于同一个集合无需合并
if (xRoot == yRoot) {
return;
}
//属于不同的集合则需要合并
parent[xRoot] = yRoot;
}
}