要求:把被围起来的o改成x但是o在边界的话全都不能改
思路:dfs,当然bfs和并查集也行,用了个数组存了改过的元素发现有o在边界的全部改回来,一遍过了
class Solution {
public:
void dfs(vector<vector<char>>& board,vector<pair<int,int>> &o,int i,int j,bool &addright){
if(i<0||i>=board.size()||j<0||j>=board[0].size()||board[i][j]=='X')return;
if(i==0||i+1==board.size()||j==0||j+1==board[0].size()){
addright=false;
return;
}
board[i][j]='X';
o.push_back(make_pair(i,j));
int di[4]={0,0,1,-1};
int dj[4]={1,-1,0,0};
for(int k=0;k<4;++k)
dfs(board,o,i+di[k],j+dj[k],addright);
}
void solve(vector<vector<char>>& board) {
for(int i=1;i+1<board.size();++i)
for(int j=1;j+1<board[0].size();++j)
if(board[i][j]=='O'){
vector<pair<int,int>> o;
bool addright=true;
dfs(board,o,i,j,addright);
if(!addright)
for(auto p:o)
board[p.first][p.second]='O';
}
}
};