Short & Sweet DFS approach


#1
int n,m;
vector<vector<char> > a;
void dfs(vector<vector<int> > &vis,int i, int j){
    vis[i][j] = 1;
    if(i-1>=0 && !vis[i-1][j] && a[i-1][j]=='O') dfs(vis,i-1,j);
    if(j-1>=0 && !vis[i][j-1] && a[i][j-1]=='O') dfs(vis,i,j-1);
    if(i+1<n && !vis[i+1][j] && a[i+1][j]=='O') dfs(vis,i+1,j);
    if(j+1<m && !vis[i][j+1] && a[i][j+1]=='O') dfs(vis,i,j+1);
}

void Solution::solve(vector<vector<char> > &A) {
   n=A.size(), m = A[0].size();
   a = A;
   vector<vector<int> > vis(n,vector<int> (m,0));
   for(int i=0; i<n; i++){
       if(a[i][0]=='O') {  dfs(vis,i,0);}
       if(a[i][m-1]=='O') { dfs(vis,i,m-1); }
   }
   for(int i=0; i<m; i++){
       if(a[0][i]=='O') {  dfs(vis,0,i); }
       if(a[n-1][i]=='O') { dfs(vis,n-1,i); }
   }
   for(int i=0; i<n; i++){
       for(int j=0; j<m; j++){
           if(!vis[i][j]) A[i][j] = 'X';
       }
   }
}