Given a 2D board containing 'X'
and '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
思路: 两次flood fill, 第一次从上下左右四条边做flood fill, 则所有与外围联通的O都被替换成#, 然后遍历一遍整个matrix, 把仍然为O的(即sounded region)替换为X, 把#换成O
这题code ganker大神用 code = row * board[0].length + col, 来enqueue, 然后dequeue的时候用 row = code / board[0].length, col = code % board[0].length 来得到坐标值,
但是如果 board[0].length 等于4, row 等于 3, col等于8的时候, 应该是得不到正确坐标的, 题目没有说这是一个N * N的坐标系,
傻逼了。。。 col 的范围只能是 0 ~ board[0].length - 1, code = row * board[0].length + col 完全没问题。。。
所以这里自己create了一个class Node来存坐标
// This is O, not 0 in the matrix !!!
public class Solution {
static class Node{
private int i;
private int j;
public Node(int i, int j){
this.i = i;
this.j = j;
}
}
public void solve(char[][] board) {
if(board == null || board.length <= 1 || board[0].length <= 1){
return;
}
for(int j = 0; j < board[0].length; j++){
fill(board, 0, j);
fill(board, board.length - 1, j);
}
for(int i = 0; i < board.length; i++){
fill(board, i, 0);
fill(board, i, board[0].length - 1);
}
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(board[i][j] == 'O'){
board[i][j] = 'X';
}else if(board[i][j] == '#'){
board[i][j] = 'O';
}
}
}
}
private void fill(char[][] board, int i, int j){
// if(i < 0 || i >= board.length || j < 0 || j >= board[0].length){
// return;
// }
if(board[i][j] == 'O'){
board[i][j] = '#';
LinkedList<Node> queue = new LinkedList<Node>();
Node node = new Node(i, j);
queue.offer(node);
while(!queue.isEmpty()){
Node cur = queue.poll();
int row = cur.i;
int col = cur.j;
if(col > 0 && board[row][col - 1] == 'O'){
queue.offer(new Node(row, col - 1));
board[row][col - 1] = '#';
}
if(col < board[0].length - 1 && board[row][col + 1] == 'O'){
queue.offer(new Node(row, col + 1));
board[row][col + 1] = '#';
}
if(row > 0 && board[row - 1][col] == 'O'){
queue.offer(new Node(row - 1, col));
board[row - 1][col] = '#';
}
if(row < board.length - 1 && board[row + 1][col] == 'O'){
queue.offer(new Node(row + 1, col));
board[row + 1][col] = '#';
}
}
}else{
return;
}
}
}
犯了一个很二的错误。。 把O字母O看成了0 数字零, debug好几次找不出原因。。。
还有自己思考的时候总想着一遍遍历就把sounded region标记出来, 但是不知道怎么界定当前O是否是sounded, 逆向思维, 从外围联通的O开始flood fill, 则其他剩余的O就是sounded regions了, Code ganker大神的思路还是巧妙啊。。