LeetCode: Surrounded Regions 解题报告

Surrounded Regions

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

LeetCode: Surrounded Regions 解题报告

SOLUTION 1:

经典 BFS 题目。如果使用DFS,会超时。

使用队列进行BFS。注意,在判断index越界时,主页君写了2种方法。

(1)可以直接对index在0-x*y之间取。这里有个小的trick,在点在左边缘的时候,index-1会导致我们回到上一行的最右边。当然那个点也是

边缘点,所以不会造成解的错误。

(2)判断点是不是在边缘,判定上下左右还有没有节点。

常出错的点:计算index是i * cols + j  这点要记好了。

 public class Solution {
public void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) {
return;
} int rows = board.length;
int cols = board[0].length; // the first line and the last line.
for (int j = 0; j < cols; j++) {
bfs(board, 0, j);
bfs(board, rows - 1, j);
} // the left and right column
for (int i = 0; i < rows; i++) {
bfs(board, i, 0);
bfs(board, i, cols - 1);
} // capture all the nodes.
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (board[i][j] == 'O') {
board[i][j] = 'X';
} else if (board[i][j] == 'B') {
board[i][j] = 'O';
}
}
} return;
} public void bfs1(char[][] board, int i, int j) {
int rows = board.length;
int cols = board[0].length; Queue<Integer> q = new LinkedList<Integer>();
q.offer(i * cols + j); while (!q.isEmpty()) {
int index = q.poll(); // Index is out of bound.
if (index < 0 || index >= rows * cols) {
continue;
} int x = index / cols;
int y = index % cols; if (board[x][y] != 'O') {
continue;
} board[x][y] = 'B';
q.offer(index + 1);
q.offer(index - 1);
q.offer(index + cols);
q.offer(index - cols);
}
} public void bfs(char[][] board, int i, int j) {
int rows = board.length;
int cols = board[0].length; Queue<Integer> q = new LinkedList<Integer>();
q.offer(i * cols + j); while (!q.isEmpty()) {
int index = q.poll(); int x = index / cols;
int y = index % cols; if (board[x][y] != 'O') {
continue;
} board[x][y] = 'B';
if (y < cols - 1) {
q.offer(index + 1);
} if (y > 0) {
q.offer(index - 1);
} if (x > 0) {
q.offer(index - cols);
} if (x < rows - 1) {
q.offer(index + cols);
}
}
}
}

SOLUTION 2:

附上DFS解法:

 public void dfs(char[][] board, int i, int j) {
int rows = board.length;
int cols = board[0].length; // out of bound or visited.
if (i < 0 || i >= rows || j < 0 || j >= cols) {
return;
} if (board[i][j] != 'O') {
return;
} board[i][j] = 'B'; // dfs the sorrounded regions.
dfs(board, i + 1, j);
dfs(board, i - 1, j);
dfs(board, i, j + 1);
dfs(board, i, j - 1);
}

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/bfs/Solve.java

上一篇:iOS: 学习笔记, Swift与C指针交互(译)


下一篇:[leetcode]Surrounded Regions @ Python