给定一个二维的矩阵,包含 'X'
和 'O'
(字母 O)。
找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
示例:
X X X X X O O X X X O X X O X X
运行你的函数后,矩阵变为:
X X X X X X X X X X X X X O X X
解释:
被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O'
都不会被填充为 'X'
。 任何不在边界上,或不与边界上的 'O'
相连的 'O'
最终都会被填充为 'X'
。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
public void solve(char[][] board) {
if (board.length <= 0)
return;
int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < cols; i++) {
if (board[0][i] == 'O')
bfs(board, 0, i);
if (board[rows - 1][i] == 'O')
bfs(board, rows - 1, i);
}
for (int i = 0; i < rows; i++) {
if (board[i][0] == 'O')
bfs(board, i, 0);
if (board[i][cols - 1] == 'O')
bfs(board, i, cols - 1);
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'O')
board[i][j] = 'X';
if (board[i][j] == '+')
board[i][j] = 'O';
}
}
}
private void bfs(char[][] board, int i, int j) {
Integer rows = board.length;
Integer cols = board[0].length;
Integer[][] dir = { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };
Queue<Integer[]> queue = new LinkedList<Integer[]>();
board[i][j] = '+';
queue.offer(new Integer[] { i, j });
while (!queue.isEmpty() && queue.size() > 0) {
Integer[] temp = queue.poll();
for (int k = 0; k < 4; k++) {
Integer next_i = temp[0] + dir[k][0];
Integer next_j = temp[1] + dir[k][1];
if (next_i < 0 || next_i >= rows || next_j < 0 || next_j >= cols || board[next_i][next_j] != 'O')
continue;
board[next_i][next_j] = '+';
queue.offer(new Integer[] { next_i, next_j });
}
}
}