题目:被围绕的区域
思路:
好吧,这题不会。
bfs+递归 dfs+非递归 dfs+并查集 - 被围绕的区域 - 力扣(LeetCode)
将问题转化为与边界O相连的O。有点像岛屿问题了。
代码是:
//code
class Solution {
public:
void dfs(vector<vector<char>>& board , int i, int j){
if(i<0 || j<0 || i >=board.size() || j >= board[0].size() || board[i][j]=='X' || board[i][j]=='#'){
return ;
}
board[i][j]='#';
dfs(board,i-1,j);
dfs(board,i+1,j);
dfs(board,i,j-1);
dfs(board,i,j+1);
}
void solve(vector<vector<char>>& board) {
//if(board.size()==0) return;
int row = board.size();
int col = board[0].size();
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
bool isedge = (i==0 || j == 0 || i==row-1 || j==col-1);
if(isedge && board[i][j]=='O'){
dfs(board,i,j);
}
}
}
for(int i=0;i<row;i++){
for(int j = 0;j<col;j++){
switch(board[i][j]){
case('#'):
board[i][j]='O';
break;
case('O'):
board[i][j]='X';
break;
}
}
}
}
};