原题地址:https://oj.leetcode.com/problems/surrounded-regions/
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
思路:所有O中需要保留的O为从最外层的为’O‘的点出发,能到达的所有O,其他的则变为X。显然又是图的遍历问题。相邻上下左右相同的点之间有边。利用图的BFS,通过将已访问的O标记为”#“来标记已访问的点。最后通过全数组扫描。为”O“的说明不可达,变为X,为”#“的还原成”O“。感觉很想java虚拟机中GC寻找不可达的对象。
public class Solution {
public void solve(char[][] board) {
if (board == null) {
return;
}
int rows = board.length;
if (rows < 3) {
return;
}
int cols = board[0].length;
if (cols < 3) {
return;
}
for (int i = 0; i < cols; i++) {
fill(board, 0, i);
fill(board, rows - 1, i);
}
for (int i = 1; i < rows - 1; i++) {
fill(board, i, 0);
fill(board, i, cols - 1);
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == '#') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
//BFS
private void fill (char[][] board, int i, int j) {
if (board[i][j] != 'O') {
return;
}
int cols = board[0].length;
Queue<Integer> queue = new LinkedList<Integer>();
board[i][j] = '#';
int index = i * cols + j;
queue.offer(index);
while (!queue.isEmpty()) {
int point = queue.poll();
int row = point / cols;
int col = point % cols;
// up
if (row > 0 && board[row - 1][col] == 'O') {
board[row - 1][col] = '#';
queue.offer((row - 1) * cols + col);
}
// down
if (row < board.length - 1 && board[row + 1][col] == 'O') {
board[row + 1][col] = '#';
queue.offer((row + 1) * cols + col);
}
// left
if (col > 0 && board[row][col - 1] == 'O') {
board[row][col - 1] = '#';
queue.offer(row * cols + col - 1);
}
// right
if (col < board[0].length - 1 && board[row][col + 1] == 'O') {
board[row][col + 1] = '#';
queue.offer(row * cols + col + 1);
}
}
}
}