What is the problem with my code, please help


  • 0
    R

    Hi, I used the normal idea of the connected components, on judge I got wrong answer for an input, but the input is so big that I could see what is happening, and for the small testcases I tested the code works fine. can anyone see the error? thanks

    class Solution {
    public:
        int numIslands(vector<vector<char>>& grid) {
            char num='1';
            for(int i=0; i<grid.size(); ++i){
                for(int j=0; j<grid[0].size(); ++j){
                    if(grid[i][j]=='1'){
                        num=num+1;
                        BFS(grid, num, i, j);
                    }
                }
            }
            return num=='1'?0: (num-'0')-1;
        }
    private:
        void BFS(vector<vector<char>>& grid, char num, int i, int j){
            int rows=grid.size(), cols=grid[0].size();
            int code=i*cols+j;
            queue<int>q;
            q.push(code);
            while(!q.empty()){
                int c=q.front(); 
                q.pop();
                int y=c%cols;
                int x=c/cols;
                if(y<cols-1 && grid[x][y+1]=='1'){
                    grid[x][y+1]=num;
                    q.push(x*cols+y+1);
                }
                if(y>0 && grid[x][y-1]=='1'){
                    grid[x][y-1]=num;
                    q.push(x*cols+y-1);
                }
                if(x<rows-1 && grid[x+1][y]=='1'){
                    grid[x+1][y]=num;
                    q.push((x+1)*cols+y);
                }
                if(x>0 && grid[x-1][y]=='1'){
                    grid[x-1][y]=num;
                    q.push((x-1)*cols+y);
                }
            }
        }
    };

Log in to reply
 

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