Please tell what's wrong in this really easy DFS C++ approach?


#1
void dfs(vector<vector<char>> &A, int r, int c){
    if(r<0 or c<0 or r>=A.size() or c>=A[0].size() or A[r][c]!='O') return;
    A[r][c]='B';
    dfs(A, r+1, c);
    dfs(A, r-1, c);
    dfs(A, r, c+1);
    dfs(A, r, c-1);
}

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

#2

In solve function, in the if statement, no matter what the value of i and j is (i.e., the index that you are concerned with at the instant), you are checking for boundary cells ALWAYS like for eg that of lower wall(i == rows - 1 && j is varying) : that condition will always be true because you have still not reached there…you are working on lets say upper wall…but then on the basis of your condition for lower wall you are making the call for current i and j. That is something that is creating the problem I think. condition of if statement is not dependent on the current value of i and j…its operating on the basis of some constant fact not on the basis of your current value of i and j. Hope its clear!