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
DFS会StackOverFlow,网上有解法说可以用非递归的DFS,http://blog.csdn.net/linhuanmars/article/details/22904855
当然不用DFS的话,就用BFS了。要注意的是:保存一个全局二维数组记录已经遍历过的节点
import java.util.ArrayList;
import java.util.List;
class Point {
int i, j;
public Point(int i, int j) {
this.i = i;
this.j = j;
}
}
/*
* 用BFS
*/
public class Solution {
boolean f = false;
int[] diff1 = new int[]{0,0,1,-1};
int[] diff2 = new int[]{1,-1,0,0};
boolean[][] marked;
public void solve(char[][] board) {
if(board == null || board.length == 0) return;
marked = new boolean[board.length][board[0].length];
for(int i=1; i<board.length-1; i++) {
for(int j=1; j<board[0].length-1; j++) {
if(board[i][j] == 'O' && !marked[i][j])
bfs(board, i, j);
}
}
}
private void bfs(char[][] board, int i, int j) {
List<Point> list = new ArrayList<Point>();
List<Point> next = new ArrayList<Point>();
List<Point> path = new ArrayList<Point>();
boolean f = true;
marked[i][j] = true;
list.add(new Point(i, j));
while(!list.isEmpty()) {
for(Point p : list) {
if(p.i == 0 || p.i == board.length-1 || p.j == 0 || p.j == board[0].length-1) {
f = false;
}
for(int k=0; k<4; k++) {
int newi = p.i+diff1[k], newj = p.j+diff2[k];
if(newi >=0 && newi < board.length &&
newj >=0 && newj < board[0].length &&
!marked[newi][newj] && board[newi][newj] == 'O') {
next.add(new Point(newi, newj));
marked[newi][newj] = true;
}
}
}
if(!list.isEmpty()) path.addAll(list);
list = next;
next = new ArrayList<Point>();
}
if(f) {
for(Point p : path)
board[p.i][p.j] = 'X';
}
}
}