参考:http://blog.csdn.net/worldwindjp/article/details/19251995
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
**主要学到:
四个方向遍历时候的简洁代码,bfs学习。**
AC代码:
public class Solution {
public void solve(char[][] board) {
if(board == null || board.length<=0){
return ;
}
int lenX = board.length;
int lenY = board[0].length;
Deque<Integer> queue = new ArrayDeque<>();
for(int i=0; i<lenX; i++){
for(int j=0; j<lenY; j++){
if(i==0||j==0||i==lenX-1 || j==lenY-1){
if(board[i][j]=='O'){
queue.offer(i*lenY+j);
}
}
}
}
//四个方向的数组表示
int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}};
//标识阶段,将不能被包围的全部标识一遍
while(queue.size()>0){
int pos = queue.poll();
int posX = pos/lenY;
int posY = pos%lenY;
if(board[posX][posY]=='Y'){
continue;
}
board[posX][posY] = 'Y';
//向四个方向扩展
for(int k=0; k<4; k++){
int x = posX + dir[k][0];
int y = posY + dir[k][1];
if(x<lenX && x>=0 && y>=0 && y<lenY && board[x][y]=='O'){
queue.offer(x*lenY+y);
}
}
}
for(int i=0; i<lenX; i++){
for(int j=0; j<lenY; j++){
if(board[i][j]=='Y'){
board[i][j]='O';
}else if(board[i][j]=='O'){
board[i][j]='X';
}
}
}
}
}