Surrounded Regions
Total Accepted: 4485 Total Submissions: 31870 My Submissions
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
Discuss
个人感觉这个题目和九度 题目1460:Oil Deposit很像,解题思路参考( Jobdu 题目1460:Oil Deposit),各位不妨思考一下相似之处。
好吧,我承认第一遍看这个题目有点不太懂。
其实题目大意是这样的,从一个二维矩阵中寻找所有被X包围的O,如果找到的话,将所有的O替换为X。
BFS,基本思路是从边界开始找起,同时标记是否访问过,防止重复搜索。如果边界有O的话,从该点开始宽度优先搜索,搜索到O就标记访问过。针对每个边界上为O的点搜索,这样就可以搜索到结果。搜索完毕之后,所有的为O的未访问过的点,都为被X包围的点,直接赋值为X即可。
Total Accepted: 4485 Total Submissions: 31870 My Submissions
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
Discuss
个人感觉这个题目和九度 题目1460:Oil Deposit很像,解题思路参考( Jobdu 题目1460:Oil Deposit),各位不妨思考一下相似之处。
好吧,我承认第一遍看这个题目有点不太懂。
其实题目大意是这样的,从一个二维矩阵中寻找所有被X包围的O,如果找到的话,将所有的O替换为X。
BFS,基本思路是从边界开始找起,同时标记是否访问过,防止重复搜索。如果边界有O的话,从该点开始宽度优先搜索,搜索到O就标记访问过。针对每个边界上为O的点搜索,这样就可以搜索到结果。搜索完毕之后,所有的为O的未访问过的点,都为被X包围的点,直接赋值为X即可。
Java AC
public class Solution {
public int stepArr[][] = {{-1,0},{1,0},{0,-1},{0,1}};
public int visit[][];
public int m, n;
public void solve(char[][] board) {
if(board == null || board.length == 0){
return;
}
m = board.length;
n = board[0].length;
visit = new int[m][n];
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if((i == 0 || i == m-1 || j == 0 || j == n-1)
&& visit[i][j] == 0 && board[i][j] == 'O'){
bfs(i,j,board);
}
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(visit[i][j] != 1 && board[i][j] == 'O'){
board[i][j] = 'X';
}
}
}
}
public void bfs(int nodei, int nodej, char board[][]){
Queue<Node> queue = new LinkedList<Node>();
Node node = new Node(nodei, nodej);
queue.offer(node);
visit[nodei][nodej] = 1;
while(!queue.isEmpty()){
node = queue.peek();
queue.poll();
int newx = 0;
int newy = 0;
for(int i = 0; i < 4; i++){
newx = node.x + stepArr[i][0];
newy = node.y + stepArr[i][1];
if(newx >= 0 && newx < m && newy >= 0 && newy < n
&& visit[newx][newy] == 0 && board[newx][newy] == 'O'){
visit[newx][newy] = 1;
queue.offer(new Node(newx, newy));
}
}
}
}
public class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
}