Change 'O' surrounded by 'x' to 'x '.
Method: Start from the peripheral 'O' and find the connectable 'O', then these 'O' will not be marked in the end, and the remaining 'O' will be marked. Here, we can mark the 'O' that can be traversed from the peripheral 'O' as another character, and then restore it in a unified manner. Method 2: it can also be explored from all 'O'. As long as it cannot be explored beyond the boundary, the intermediate nodes can be saved in a stack.
Implementation: BFS (using DFS will blow up stack re ...)
int dir[4][2]={-1,0,1,0,0,-1,0,1};struct Node{ int x,y;};class Solution {public: int n,len,m; Node*Q; void bfs(int stx,int sty,vector<vector<char> > &b){ int front=-1,rear=-1,len=n*m; Node p,q; p.x=stx,p.y=sty; b[p.x][p.y]='F'; Q[++rear]=p; int i,dx,dy; while(front!=rear){ front=(front+1)%len; q=Q[front]; // if(b[q.x][q.y]!='O')continue; for(i=0;i<4;++i){ p.x=q.x+dir[i][0]; p.y=q.y+dir[i][1]; if(p.x<0||p.y<0||p.x>=n||p.y>=m||b[p.x][p.y]!='O') continue; b[p.x][p.y]='F'; rear=(rear+1)%len; Q[rear]=p; } } } void solve(vector<vector<char> > &b) { if(b.size()<=0)return; int i,j,k; n=b.size(); m=b[0].size(); Q=new Node[n*m]; for(i=0;i<m;++i){ if(b[0][i]=='O')bfs(0,i,b); if(b[n-1][i]=='O')bfs(n-1,i,b); } for(i=1;i<n-1;++i){ if(b[i][0]=='O')bfs(i,0,b); if(b[i][m-1]=='O')bfs(i,m-1,b); } for(i=0;i<n;++i){ m=b[i].size(); for(j=0;j<m;++j) { if(b[i][j]=='F')b[i][j]='O'; else if(b[i][j]=='O')b[i][j]='X'; } } delete[]Q; }};
[Leetcode] surrounded regions