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
('D'站位的思路来自Peking2,二爷)
好,普通数字组合dfs和一维dfs我们已经攻克了,那么我们进军到平面上的dfs问题(具体点是矩阵里的dfs)
其实思路都一样的,如果说一维我们只能向前走这一个方向,那么二维,我们就有上,下,左,右四个方向可以走
这道题的切入点就是如果O区域和边界联结上,那么就不可能被X所包围,换句话和边界联接上的O,我们需要保留,而不和边界联通区域的O,都将被X所吞噬 我们可以从边界运用dfs,只要是O,便转化为另一个字母D,这样,等dfs都结束后,最后我们再扫一遍board,如果还存在O,便证明是处于中间区域,都转化为X, 所有字母D的区域,便都是和边界相邻的O,我们将他们还原成O
public class Solution {
public void solve(char[][] board) {
if (board==null||board.length==0) return;
int row = board.length;
int col = board[0].length;
for(int j=0;j<col;j++){
dfs(board,0,j);
dfs(board,row-1,j); //第一行和最后一行
}
for(int i=1;i<row-1;i++){
dfs(board,i,0);
dfs(board,i,col-1); //第一列和最后一列抛去和上一个循环相交的格子
}
for(int i=0;i<row;i++)
for(int j=0;j<col;j++){
if (board[i][j]=='D') board[i][j] = 'O';
else if (board[i][j]=='O') board[i][j] = 'X';
}
}
public void dfs(char[][] board, int x, int y){
if (x<0||x>=board.length||y<0||y>=board[0].length||board[x][y]!='O') return;
board[x][y] = 'D';
dfs(board,x-1,y);
dfs(board,x+1,y);
dfs(board,x,y-1);
dfs(board,x,y+1);
}
}
dfs的思想非常直观,不过跑大数据的时候会超时,因为递归太深的缘故
我们可以运用同样的思路,改写成bfs,顺便用dir[]来代表方向,让代码看着整洁一些 (不过我改写的bfs依旧会超时,如果有好的方法,请留言)
public class Solution {
Queue<Integer> queue = new LinkedList<Integer>();
public void solve(char[][] board) {
if (board==null||board.length==0) return;
int row = board.length;
int col = board[0].length;
for(int j=0;j<col;j++){
bfs(board,0,j);
bfs(board,row-1,j);
}
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]=='D') board[i][j] = 'O';
else if (board[i][j]=='O') board[i][j] = 'X';
}
}
public void bfs(char[][] board, int x, int y){
int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
int row = board.length;
int col = board[0].length;
if (board[x][y]=='O') queue.offer(x*row+y);
while(queue.size()>0){
int tmp = queue.poll();
x = tmp/row;
y = tmp%row;
board[x][y] = 'D';
for(int[] d:dir){
int i = x + d[0];
int j = y + d[1];
if (i>=0 && i<row && j>=0 && j<col && board[i][j]=='O')
queue.offer(i * row + j);
}
}
}
}