VERY EASY AND SMALL C++ SOL. (checking from boundaries only concept!)


#1
vector<pair<int,int>> steps={make_pair(1,0),make_pair(0,-1),make_pair(-1,0),make_pair(0,1)};
bool isSafe(int i,int j,vector<vector<char> > &A)
{
    return (i>=0)&&(i<A.size())&&(j>=0)&&(j<A[0].size())&&(A[i][j]=='O');
}
void dfs(int i,int j,vector<vector<char> > &A)
{
    A[i][j]='+'; //dummy symbol
    for(int k=0;k<4;k++)
        if(isSafe(i+steps[k].first,j+steps[k].second,A))
            dfs(i+steps[k].first,j+steps[k].second,A);
}
void Solution::solve(vector<vector<char> > &A) {
    int r=A.size(),c=A[0].size();
    for(int j=0;j<c;j++){ //checking boundaries only
        if(A[0][j]=='O') dfs(0,j,A);
        if(A[r-1][j]=='O') dfs(r-1,j,A); }
        
    for(int i=0;i<r;i++){ //checking boundaries only
        if(A[i][0]=='O') dfs(i,0,A);
        if(A[i][c-1]=='O') dfs(i,c-1,A); }
    
    for(int i=0;i<r;i++){
        for(int j=0;j<c;j++){
            if(A[i][j]=='+') A[i][j]='O'; //replacing dummy symbol
            else A[i][j] = 'X';
        }
    }
}

#2

bool issafe(vector<vector>arr,int i,int j,int rows,int cols)
{
return (i<rows)&&(j<cols)&&(i>=0)&&(j>=0)&&(arr[i][j]==‘O’);
}
int xarr[]={1,-1,0,0};
int yarr[]={0,0,1,-1};
void applybfs(int i,int j,int rows,int cols,vector<vector>&arr)
{
arr[i][j]=‘B’;
for(int k=0;k<4;k++)
{
if(issafe(arr,i+xarr[k],j+yarr[k],rows,cols))
{
applybfs(i+xarr[k],j+yarr[k],rows,cols,arr);
}
}
}
void Solution::solve(vector<vector>&arr) {
int rows=arr.size();
int cols=arr[0].size();
for(int i=0;i<rows;i++)
{
if(arr[i][0]==‘O’)
{
applybfs(i,0,rows,cols,arr);
}
if(arr[i][cols-1]==‘O’)
{
applybfs(i,cols-1,rows,cols,arr);
}
}
for(int i=1;i<cols-1;i++)
{
if(arr[0][i]==‘O’)
{
applybfs(0,i,rows,cols,arr);
}
if(arr[rows-1][i]==‘O’)
{
applybfs(rows-1,i,rows,cols,arr);
}
}
for(int i=0;i<rows;i++)
{
for(int j=0;j<cols;j++)
{
if(arr[i][j]==‘O’)
arr[i][j]=‘X’;
if(arr[i][j]==‘B’)
arr[i][j]=‘O’;
}
}
}
// Bro , My solution is very similar to urs, but got TLE. Can you check my solution? I shall be Really thankful to you!