Doddi girish
Doddi girish

Reputation: 115

i am getting error while running the code

This is Leetcode 200.The question statement is: Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

11110
11010
11000
00000

Output: 1

while trying to solve this i am getting the error reference binding to null pointer of type 'std::vector >' (stl_vector.h)

I was getting correct answer for some inputs but overall when i submit it i am getting above error.i would appreciate if anyone can help me with this.

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        int count=0;
        int n=grid.size();
        int m=grid[0].size();
        if(grid.size()==0 || grid[0].size()==0)
            return 0;
        bool left,right,top,bottum;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
            {
                   if(grid[i][j]=='1')
                   {
                       count++;
                       BFS(grid,i,j);
                   }
            }
        return count;
}
   void BFS(vector< vector <char> >& grids,int i,int j)
   {
       if(i<0 || j<0 || i>=grids.size() || j>=grids[0].size() || grids[i][j]=='0')
           return ;
       grids[i][j]='0';
       BFS(grids,i+1,j);
       BFS(grids,i,j+1);
       BFS(grids,i-1,j);
       BFS(grids,i,j-1);
   }
};

Upvotes: 0

Views: 85

Answers (1)

john
john

Reputation: 88092

These three statements are in the wrong order

    int n=grid.size();
    int m=grid[0].size(); // <-- problem here
    if(grid.size()==0 || grid[0].size()==0)
        return 0;

it should be

    if(grid.size()==0 || grid[0].size()==0)
        return 0;
    int n=grid.size();
    int m=grid[0].size();

otherwise you get a crash accessing grid[0] when grid.size() equals zero.

Upvotes: 1

Related Questions