130 Surrounded Regions – Medium
Problem:
Thoughts:
Solutions:
public class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0){
return;
}
LinkedList<Integer> xs = new LinkedList<Integer>();
LinkedList<Integer> ys = new LinkedList<Integer>();
initStarter(xs, ys, board);
markO(xs, ys, board);
flipBoard(board);
}
//add all loc of edge 'O' to queue
private void initStarter(LinkedList<Integer> xs, LinkedList<Integer> ys, char[][] board){
int height = board.length;
int width = board[0].length;
for (int i = 0; i < height; i ++){
if (board[i][0] == 'O'){
xs.add(i);
ys.add(0);
}
if (board[i][width-1] == 'O'){
xs.add(i);
ys.add(width-1);
}
}//for i
for (int j = 0; j < width; j ++ ){
if (board[0][j] == 'O'){
xs.add(0);
ys.add(j);
}
if (board[height - 1][j] == 'O'){
xs.add(height - 1);
ys.add(j);
}
}//for j
}
//mark all unsurronded O with Y
private void markO(LinkedList<Integer> xs, LinkedList<Integer> ys, char[][] board){
int height = board.length;
int width = board[0].length;
//use Y stands for unsurronded O
while (xs.size() > 0){
int x = xs.pop();
int y = ys.pop();
board[x][y] = 'Y';
if (x - 1 >= 0 && board[x-1][y] == 'O'){
xs.add(x-1);
ys.add(y);
}
if (x + 1 < height && board[x+1][y] == 'O'){
xs.add(x+1);
ys.add(y);
}
if (y - 1 >= 0 && board[x][y-1] == 'O'){
xs.add(x);
ys.add(y-1);
}
if (y + 1 < width && board[x][y+1] == 'O'){
xs.add(x);
ys.add(y+1);
}
}//while
}
private void flipBoard(char[][] board){
int height = board.length;
int width = board[0].length;
for (int i = 0; i < height; i ++){
for (int j = 0; j < width; j ++){
if (board[i][j] == 'Y')
board[i][j] = 'O';
else
board[i][j] = 'X';
}
}
}//flipBoard
}Last updated