What is wrong in initializing the global count variable"ct=0". I'm getting incorrect result for the following test case.


  • 0
    S

    Input: ["11000","11000","00100","00011"]
    Output: 4
    Expected: 3

    int ri[]={-1,0,0,1};
    int ci[]={0,-1,1,0};
    
    int ct=0; //initialized the global count variable to 0.
    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
        vector<vector<char>>& A=grid;
        m=A.size();
        
        if (m==0)
         return 0;
        n=A[0].size();
        
        vector<vector<bool>>v (m,vector<bool>(n,false));
        
        for (int i=0; i<m; i++)
        {
            for (int j=0; j<n; j++)
            {
                if (A[i][j]=='1' && v[i][j]==false)
                {
                    ct++; //using it here..
                    dfs(A,v,i,j);
                }
                  
            }
        }
        
        return ct;
        }
        
    private:
        int m;
        int n;
    void dfs(vector<vector<char>>&A, vector<vector<bool>>&v, int r, int c)
    {
        v[r][c]=true;
        for (int i=0; i<4; i++)
        {
            int nr=r+ri[i];
            int nc=c+ci[i];
            
            if (nr>=0 && nr<m && nc>=0 && nc<n && A[nr][nc]=='1' && v[nr][nc]==false)
                dfs(A,v,nr,nc);
        }
    }
    };```

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.