130. Surrounded Regions
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
因为最外层的不会被包围,那如果最外层某个位置为O,那么紧挨着它的所有位置的O都不会被包围,因此,实际上是使用BFS的方法,利用一个队列的数据结构。
原始版:
class Node {
int row;
int col;
public Node(int row, int col) {
this.row = row;
this.col = col;
}
}
public void solve(char[][] board) {
if (board == null || board.length == 0)
return;
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
Queue<Character> q = new LinkedList<>();
// 第一行和最后一行
for (int i = 0; i < n; i++) {
if (!visited[0][i] && board[0][i] == 'O')
bfs(board, 0, i, m, n, visited);
if (!visited[m - 1][i] && board[m - 1][i] == '