题目:
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.
解答:
题目中给出了解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 ‘O’ 都不会被填充为 ‘X’。 任何不在边界上,或不与边界上的 ‘O’ 相连的 ‘O’ 最终都会被填充为 ‘X’。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
所以思路是:
- 遍历数组的边界,从边界开始寻找‘O’,并将坐标入队列
- 从边界开始寻找与之相连的‘O’,将边界及边界相连的‘O’都暂时改为‘#’进行标记
- 最后遍历数组,将数组中的‘O’改为‘X’,并将‘#’改为‘O’
class Solution {
public void solve(char[][] board) {
int row = board.length; //行数
if(row == 0) return;
int column = board[0].length; //列数
Queue<Integer[]> queue = new LinkedList<>(); //保存O的位置
for(int i=0; i<column; i++) { //寻找第一行中的‘O’
if(board[0][i] == 'O') {
Integer[] index = {0, i};
queue.add(index);
}
}
for(int i=0; i<column; i++) { //寻找最后一行中的‘O’
if(board[row-1][i] == 'O') {
Integer[] index = {row-1, i};
queue.add(index);
}
}
for(int i=0; i<row; i++) { //寻找第一列中的‘O’
if(board[i][0] == 'O') {
Integer[] index = {i, 0};
queue.add(index);
}
}
for(int i=0; i<row; i++) { //寻找最后一列中的‘O’
if(board[i][column-1] == 'O') {
Integer[] index = {i, column-1};
queue.add(index);
}
}
while(!queue.isEmpty()) {
Integer[] index = queue.poll();
int m = index[0]; //行数
int n = index[1]; //列数
board[m][n] = '#'; //将边界的‘O’改为‘#’,标记为不需要转换的
if(m>=1 && board[m-1][n]=='O') { //判断该点的上方
Integer[] temp = {m-1, n};
queue.add(temp);
}
if(m<row-1 && board[m+1][n]=='O') { //判断该点的下方
Integer[] temp = {m+1, n};
queue.add(temp);
}
if(n>=1 && board[m][n-1]=='O') { //判断该点的左边
Integer[] temp = {m, n-1};
queue.add(temp);
}
if(n<column-1 && board[m][n+1]=='O') { //判断该点的右边
Integer[] temp = {m, n+1};
queue.add(temp);
}
}
for(int i=0; i<row; i++) {
for(int j=0; j<column; j++) {
if(board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
for(int i=0; i<row; i++) {
for(int j=0; j<column; j++) {
if(board[i][j] == '#') {
board[i][j] = 'O';
}
}
}
return;
}
}