130. 被围绕的区域
130. 被围绕的区域
给你一个 m x n
的矩阵 board
,由若干字符 'X'
和 'O'
,找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
示例 1:
输入:board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
输出:[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
解释:被围绕的区间不会存在于边界上,换句话说,任何边界上的 'O' 都不会被填充为 'X'。 任何不在边界上,或不与边界上的 'O' 相连的 'O' 最终都会被填充为 'X'。如果两个元素在水平或垂直方向相邻,则称它们是“相连”的。
示例 2:
输入:board = [["X"]]
输出:[["X"]]
提示:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
为'X'
或'O'
思路:
本题与岛屿问题类似,可以先处理边界,然后再去DFS内部的连通,最后还原边界即可。
class Solution {
public:
void solve(vector<vector<char>>& board) {
int m=board.size();
int n=board[0].size();
//从边界开始DFS,把所有与边连通的O变为A
for(int i=0;i<m;i++){
if(board[i][0]=='O')vDFS(board,i,0,m,n);
if(board[i][n-1]=='O')vDFS(board,i,n-1,m,n);
}
for(int i=0;i<n;i++){
if(board[0][i]=='O')vDFS(board,0,i,m,n);
if(board[m-1][i]=='O')vDFS(board,m-1,i,m,n);
}
//从内部DFS
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='O'){
DFS(board,i,j,m,n);
}
}
}
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(board[i][j]=='A'){
board[i][j]='O';
}
}
}
}
void vDFS(vector<vector<char>>& board,int x,int y,int m,int n){
if(x<0||y<0||x>=m||y>=n)return;
if(board[x][y]=='X'||board[x][y]=='A')return;
board[x][y]='A';
vDFS(board,x,y-1,m,n);
vDFS(board,x,y+1,m,n);
vDFS(board,x-1,y,m,n);
vDFS(board,x+1,y,m,n);
}
void DFS(vector<vector<char>>& board,int x,int y,int m,int n){
if(x<0||y<0||x>=m||y>=n)return;
if(board[x][y]=='X')return;
board[x][y]='X';
DFS(board,x,y-1,m,n);
DFS(board,x,y+1,m,n);
DFS(board,x-1,y,m,n);
DFS(board,x+1,y,m,n);
}
};
本文来自博客园,作者:{BailanZ},转载请注明原文链接:https://www.cnblogs.com/BailanZ/p/16133841.html