填充封闭区域
130. Surrounded Regions (Medium)
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
题目描述:
使被'X'包围的‘O’转换为'X'。
思路分析:
我们先将与边界上所有O相联通的O标记,然后遍历数组,遇见未被标记的O就将其换成X,这样就能保证所有被X包围的O都被替换成X。
代码:
class Solution {
public void solve(char [][]board){
if(board==null||board.length==0)
return ;
int m=board.length;
int n=board[0].length;
for(int i=0;i<n;i++){
if(board[0][i]=='O'){ //上边界
dfs(board,0,i);
}
if(board[m-1][i]=='O'){ //下边界
dfs(board,m-1,i);
}
}
for(int j=0;j<m;j++){
if(board[j][0]=='O')
dfs(board,j,0);
if(board[j][n-1]=='O')
dfs(board,j,n-1);
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='O')
board[i][j]='X';
if(board[i][j]=='0')//与边界联通的O
board[i][j]='O';
}
}
return;
}
public void dfs(char[][]board,int i,int j){ //标记与边界O相连的O
if(board[i][j]!='O')
return ;
board[i][j]='0';
if(i+1<board.length)
dfs(board,i+1,j);
if(i-1>=0)
dfs(board,i-1,j);
if(j+1<board[0].length)
dfs(board,i,j+1);
if(j-1>=0)
dfs(board,i,j-1);
}
}