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 XAfter running your function, the board should be:
X X X X X X X X X X X X X O X X题目的大意是指,将被'X'包围区域内的'o'替换为'X',而对于未被包围的区域不用替换,可采用Dfs进行搜索边界上未被包围的'o',或者采用BFS的方法。
采用的java 递归的DFS方法出现了Runtime error,stack overflow,改为用栈实现递归。代码如下:
public class Solution {
public void solve(char[][] board) {
if(board==null||board.length==0)
return;
int m,n;
m=board.length;
n=board[0].length;
for(int i=0;i<m;i++)
{
if(board[i][0]=='O') DFS(board,i,0);
if(board[i][n-1]=='O') DFS(board,i,n-1);
}
for(int j=1;j<n-1;j++)
{
if(board[0][j]=='O') DFS(board,0,j);
if(board[m-1][j]=='O') DFS(board,m-1,j);
}
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(board[i][j]=='O')
board[i][j]='X';
else if(board[i][j]=='D')
board[i][j]='O';
}
}
public void DFS(char[][] board,int x,int y)
{
if(x<0||x>=board.length||y<0||y>=board[0].length) return;
Stack<Integer> stack=new Stack<Integer>();
stack.push(x*board[0].length+y);
while(!stack.empty())
{
int curr=stack.pop();
int i=curr/board[0].length;
int j=curr%board[0].length;
board[i][j]='D';
if(i>0&&board[i-1][j]=='O')
stack.push((i-1)*board[0].length+j);
if(i<board.length-1&&board[i+1][j]=='O')
stack.push((i+1)*board[0].length+j);
if(j>0&&board[i][j-1]=='O')
stack.push(i*board[0].length+j-1);
if(j<board[0].length-1&&board[i][j+1]=='O')
stack.push(i*board[0].length+j+1);
}
}
}
采用BFS实现的代码如下,使用队列:
public class Solution {
private int m, n;
private char[][] board;
private Queue<Integer> queue = new LinkedList<Integer>();
public void add(int x, int y) {
if (x >= 0 && x < m && y >= 0 && y < n && board[x][y] == 'O') {
board[x][y] = 'Z';
queue.offer(x * n + y);
}
}
public void traversal(int x, int y) {
add(x, y);
while (!queue.isEmpty()) {
int p = queue.poll();
int px = p / n;
int py = p % n;
add(px - 1, py);
add(px + 1, py);
add(px, py - 1);
add(px, py + 1);
}
}
public void solve(char[][] board) {
// Start typing your Java solution below
// DO NOT write main() function
if (board == null || board.length == 0 || board[0].length == 0) {
return;
}
this.board = board;
m = board.length;
n = board[0].length;
for (int j = 0; j < n; j++) {
traversal(0, j);
traversal(m - 1, j);
}
for (int i = 0; i < m; i++) {
traversal(i, 0);
traversal(i, n - 1);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
board[i][j] = board[i][j] == 'Z' ? 'O' : 'X';
}
}
}
}
两种方法在c++中实现问题不大,但是使用java会出现Runtime error或者TLE错误,检查是否发生越界、栈溢出或者死循环等问题。