Given a 2D board containing 'X'
and 'O'
, capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
For 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
这道题的包围是指上下左右均被x包围的情况,多个O时,是一起被包围,而不是一个O被X消灭后再消灭
比如
X X X X
X O O X
X X X X
两个O外围全是X所以被消灭。
如果遍历时改变O为X,可能会影响其他O是否被消灭。
这道题可以从四周边界处开始考虑,凡是与边界O相连的O都不会被X消灭。
所以从边界O开始进行DFS或BFS。
起初用的DFS写的,java的DFS在这道题中会出现栈溢出。之后用BFS写的可以过。注意每次是将坐标入队列。
Source
public class Solution {
public void solve(char[][] board) {
if(board.length == 0) return;
for(int i = 0; i < board.length; i++){
bfs(i, 0, board);
bfs(i, board[0].length - 1, board);
}
for(int j = 0; j < board[0].length; j++){
bfs(0, j, board);
bfs(board.length - 1, j, board);
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}
else if(board[i][j] == '@'){
board[i][j] = 'O';
}
}
}
return;
}
public void bfs(int i, int j, char[][] board){
if(board[i][j] == 'X') return;
if(board[i][j] == '@') return;
LinkedList<Integer> queue = new LinkedList<Integer>();
int len = board[0].length;
board[i][j] = '@';
int a = i * len + j; //queue里面要存的是坐标 这样才能在BFS的时候传递坐标关系
queue.add(a);
while(!queue.isEmpty()){
a = queue.poll();
int r = a / len;
int c = a % len;
if(r - 1 >= 0 && board[r - 1][c] == 'O'){
board[r - 1][c] = '@';
queue.add((r - 1) * len + c);
}
if(r + 1 < board.length && board[r + 1][c] == 'O'){
board[r + 1][c] = '@';
queue.add((r + 1) * len + c);
}
if(c - 1 >= 0 && board[r][c - 1] == 'O'){
board[r][c - 1] = '@';
queue.add(r * len + c - 1);
}
if(c + 1 < len && board[r][c + 1] == 'O'){
board[r][c + 1] = '@';
queue.add(r * len + c + 1);
}
}
}
}
Test
public static void main(String[] args){
char[][] board = {{'X','O','X','X'},{'O','X','O','X'},{'X','O','X','O'},{'O','X','O','X'},{'X','O','X','O'},{'O','X','O','X'}};
new Solution().solve(board);
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
System.out.print(board[i][j]);
System.out.print(" ");
}
System.out.println();
}
}