题目
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.
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
标签:Breadth-first Search、Union Find
相似题目: (M) Number of Islands、 (M) Walls and Gates
题意
给定一个由O和X组成的矩阵,如果矩阵中的O被X包围,则将O变为X。
解题思路
参考了大神的思路:链接
自己进行了实现。
该算法用到了Flood fill
简单来说对于本题,矩阵的上下左右四个边界的“O”一定无法被“X”包围。而且所有与边界“O”相邻的“O”也无法被包围。所以结题思路就是遍历所有边界的点,若为“O”则将其置为特殊的符号“#”,并且对于这个点进行广搜,若相邻的也为“O”则置为“#”。最后对于整个矩阵,为“#”的置为“O”,为“O”的置为“X”。
源代码
public class Solution {
public void solve(char[][] board) {
if(board == null || board.length == 0 || board[0].length == 0)
return;
for(int i = 0; i < board[0].length; i ++) {
fill(board, 0, i);
fill(board, board.length - 1, i);
}
for(int i = 0; i < board.length; i ++) {
fill(board, i, 0);
fill(board, i, board[0].length - 1);
}
for(int i = 0; i < board.length; i ++) {
for(int j = 0; j < board[0].length; j ++) {
if(board[i][j] == '#')
board[i][j] = 'O';
else if(board[i][j] == 'O')
board[i][j] = 'X';
}
}
}
public void fill(char[][] board, int i, int j) {
if (board[i][j] != 'O') {
return;
}
board[i][j] = '#';
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i,j});
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
size --;
int[] pos = queue.poll();
if (pos[0] + 1 < board.length && board[pos[0] + 1][pos[1]] == 'O') {
board[pos[0] + 1][pos[1]] = '#';
queue.offer(new int[]{pos[0] + 1, pos[1]});
}
if (pos[0] - 1 >= 0 && board[pos[0] - 1][pos[1]] == 'O') {
board[pos[0] - 1][pos[1]] = '#';
queue.offer(new int[]{pos[0] - 1, pos[1]});
}
if (pos[1] + 1 < board[0].length && board[pos[0]][pos[1] + 1] == 'O') {
board[pos[0]][pos[1] + 1] = '#';
queue.offer(new int[]{pos[0], pos[1] + 1});
}
if (pos[1] - 1 >= 0 && board[pos[0]][pos[1] - 1] == 'O') {
board[pos[0]][pos[1] - 1] = '#';
queue.offer(new int[]{pos[0], pos[1] - 1});
}
}
}
}
}