leetcode 130. Surrounded Regions
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.length == 0) return;
int row = board.length;
int col = board.length;
UnionFind u = new UnionFind(row*col +1);
for(int i = 0; i< row ; i++){
for(int j = 0; j < col; j++){
if(board == 'O')
if(i == 0 || i == row -1 || j == 0 || j == col - 1){
u.union(j+ i*col , row*col);
}else{
if(board == 'O') u.union(j+i*col , j + (i-1)*col);
if(board == 'O') u.union(j+i*col , j + (i+1)*col);
if(board == 'O') u.union(j-1+i*col , j + i*col);
if(board == '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 = 'X';
}
}
}
public class UnionFind{
int[] parent;
public UnionFind(int x){
parent = new int;
for(int i = 0; i< x; i++){
parent = i;
}
}
public int find(int x){
int root = x;
while(root != parent){
parent = parent];
root = parent;
}
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_x;
}
else{
parent = root_y;
}
}
}
}
页:
[1]