马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.
class Solution {
public void solve(char[][] board) {
if(board.length == 0 || board[0].length == 0) return;
int row = board.length;
int col = board[0].length;
UnionFind u = new UnionFind(row*col +1);
for(int i = 0; i< row ; i++){
for(int j = 0; j < col; j++){
if(board[i][j] == 'O')
if(i == 0 || i == row -1 || j == 0 || j == col - 1){
u.union(j+ i*col , row*col);
}else{
if(board[i-1][j] == 'O') u.union(j+i*col , j + (i-1)*col);
if(board[i+1][j] == 'O') u.union(j+i*col , j + (i+1)*col);
if(board[i][j-1] == 'O') u.union(j-1+i*col , j + i*col);
if(board[i][j+1] == 'O') u.union(j+1+i*col , j + i*col);
}
}
}
for(int i = 0; i< row ; i++){
for(int j = 0; j< col; j++){
if(u.find(i*col+j) != col*row) board[i][j] = 'X';
}
}
}
public class UnionFind{
int[] parent;
public UnionFind(int x){
parent = new int[x];
for(int i = 0; i< x; i++){
parent[i] = i;
}
}
public int find(int x){
int root = x;
while(root != parent[root]){
parent[root] = parent[parent[root]];
root = parent[root];
}
return root;
}
public void union(int x, int y){
int root_x = find(x);
int root_y = find(y);
if(root_x == root_y)
return;
if(root_x > root_y){
parent[root_y] = root_x;
}
else{
parent[root_x] = root_y;
}
}
}
}
|