题目:
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
题意:
给定一个2维平面包含'X'
和 'O',填充所有的被
.'X'
包围的区域
比如,
X X X X
X O O X
X X O X
X O X X
运行完你的函数后,这个平面变为:
X X X X
X O O X
X X O X
X O X X
算法分析:
* 典型的BFS题目。遍历每个字符,如果是“O”,则从当前字符开始BFS遍历,如果周围也是“O”则加入当前遍历的队列,
* 直到遍历完所有相邻的“O”,于此同时,判断每个O是否是被包围的,只要由一个O是没有被包围的,
* 则当前遍历的O的集合都是没有被包围的,因为这些O都是相连的。
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution
{
public void solve(char[][] board)
{
if(board==null||board.length==0)
return;
int row=board.length;
int col=board[0].length;
boolean visited[][] = new boolean[row][col] ;//遍历标记数组
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
if(board[i][j]=='O'&&(!visited[i][j]))
{
bfs(board,i,j,visited);//若未遍历过,则对该节点进行广度优先搜索
}
}
}
}
private void bfs(char[][] board,int i,int j,boolean visited[][])
{
ArrayList<Integer> list =new ArrayList<Integer>();
Queue<Integer> queue = new LinkedList<Integer>();
boolean label=true;
int row=board.length;
int col=board[0].length;
int temjudge,temi,temj;
queue.add(i*col+j);//将数组位置二维转化为一维
visited[i][j]=true;
while(!queue.isEmpty())
{
temjudge=queue.poll();
list.add(temjudge);
temj=temjudge%col;//列位置
temi=(temjudge-temj)/col;//行位置
if(temi==0||temj==0||temi==row-1||temj==col-1)
label=false;//若该节点位于边界处,这是没有被围,所以遍历到的所有节点都不变化,这里用label记录一下
if(temj>0&&board[temi][temj-1]=='O'&&!visited[temi][temj-1])//左
{
queue.add(temi*col+temj-1);
visited[temi][temj-1]=true;
}
if(temi>0&&board[temi-1][temj]=='O'&&!visited[temi-1][temj])//上
{
queue.add((temi-1)*col+temj);
visited[temi-1][temj]=true;
}
if(temj<board[0].length-1&&board[temi][temj+1]=='O'&&!visited[temi][temj+1])//右
{
queue.add(temi*col+temj+1);
visited[temi][temj+1]=true;
}
if(temi<board.length-1&&board[temi+1][temj]=='O'&&!visited[temi+1][temj])//下
{
queue.add((temi+1)*col+temj);
visited[temi+1][temj]=true;
}
}
if(label)//遍历到的所有的节点都没有处于边界,这是对这些节点进行变化
{
for(int k=0;k<list.size();k++)
{
temjudge=list.get(k);
temj=temjudge%col;
temi=(temjudge-temj)/col;
board[temi][temj]='X';
}
}
}
}</span>