Simple Grid DFS


#1
int a[4]={1,0,-1,0};
int b[4]={0,-1,0,1};
bool safe(int x,int y,vector<vector<char> > &A){
    return (x>=0 and x<A.size() and y>=0 and y<A[0].size() and A[x][y]=='O')
}

void dfs(int x,int y,vector<vector<char>> &A){
    A[x][y]='#';
    for(int i=0;i<4;i++)
        if(safe(x+a[i],y+b[i],A)) 
            dfs(x+a[i],y+b[i],A);
}

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

#2

Really nice solution thanks