//2. 初始化连通图 int m = board.length; int n = board[0].length; UF uf = new UF(m * n + 1);
//3. 假设有个m*n节点,视为非包围O节点的根节点 int dummy = m * n;
//4. 处理前后两列 for (int i = 0; i < m; i++) { if (board[i][0] == 'O') { uf.union(i * n, dummy); } if (board[i][n - 1] == 'O') { uf.union(i * n + n - 1, dummy); } }
//5. 处理上下两行 for (int j = 0; j < n; j++) { if (board[0][j] == 'O') { uf.union(j, dummy); } if (board[m - 1][j] == 'O') { uf.union((m - 1) * n + j, dummy); } }
//6. 处理每个非边缘节点 int[][] dp = newint[][]{{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') { int p = i * n + j; for (int k = 0; k < 4; k++) { int x = i + dp[k][0]; int y = j + dp[k][1]; if (board[x][y] == 'O') { int q = x * n + y; uf.union(p, q); } } } } }
//7. 根据结果处理数组 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'; } } } } }