几个月不做 再看仍然是相当麻烦的一道题目啊
查了一下资料,使用DFS时 在大数据集合时会栈溢出,所以我们用队列来进行BFS.
只需要扫描边界,与边界连通的全部置为B, 再扫一次 原来的O置为x, B置为O,完工。
使用队列 BFS时,存入队列的元素,代表下一次准备要扫描其4个邻接点。(啊啊啊,这个逻辑超难想的,因为入队代表的是下一个要搜索它的周边,而不是要搜索它本身)
http://www.cnblogs.com/feiling/p/3304120.html
public class Solution {
public void solve(char[][] board) {
if (board == null) {
return;
}
if (board.length == 0) {
return;
}
int row = board.length;
int col = board[0].length;
// BFS the first line and the last line.
for (int i = 0; i < col; i++) {
bfs(board, 0, i);
bfs(board, row - 1, i);
}
// BFS the left line and the right line.
for (int i = 1; i < row - 1; i++) {
bfs(board, i, 0);
bfs(board, i, col - 1);
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (board[i][j] == 'B') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
return;
}
public void bfs(char[][] board, int x, int y) {
Queue
q = new LinkedList
();
// 把x, y放入queue代表准备要访问它的邻接点
visit(board, x, y, q);
while (!q.isEmpty()) {
int num = q.poll();
int r = num / board[0].length;
int c = num % board[0].length;
// visit the surrounded points.
visit(board, r + 1, c, q);
visit(board, r - 1, c, q);
visit(board, r, c + 1, q);
visit(board, r, c - 1, q);
}
return;
}
public void visit(char[][] board, int x, int y, Queue
q) {
int row = board.length;
int col = board[0].length;
if (x < 0 || x >= row || y < 0 || y >= col) {
return;
}
if (board[x][y] != 'O') {
return;
}
board[x][y] = 'B';
q.offer(col * x + y);
return;
}
}