您的位置:首页 > 其它

Number of Islands BFS

2015-06-01 17:46 281 查看


Number of Islands

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.
Example 1:
11110
11010
11000
00000

Answer: 1
Example 2:
11000
11000
00100
00011

Answer: 3

class Solution {
public:

    int numIslands(vector<vector<char>>& grid) {
        
        if(grid.empty() || grid[0].empty())
            return 0;
        int n=grid.size();
        int m=grid[0].size();
        
        int i,j,sum;
        sum=0;
        for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
            {
                if(grid[i][j]=='1')
                {
                    sum++;
                    bfs(i,j,grid,n,m);
                }
            }
        }
        return sum;
    }
    
    
    void bfs(int x,int y,vector<vector<char>> &grid,int n,int m)
    {
        queue<int> q;
        q.push(x*m+y);
        grid[x][y]='0';
        while(!q.empty())
        {
            int cur=q.front();
            q.pop();
            int xx=cur/m;
            int yy=cur%m;
            
            if(xx+1<n&&grid[xx+1][yy]=='1')
            {
                q.push((xx+1)*m+yy);
                grid[xx+1][yy]='0';
            }
            if(xx-1>=0&&grid[xx-1][yy]=='1')
            {
                q.push((xx-1)*m+yy);
                grid[xx-1][yy]='0';
            }
            if(yy+1<m&&grid[xx][yy+1]=='1')
            {
                q.push(xx*m+yy+1);
                grid[xx][yy+1]='0';
            }
             if(yy-1>=0&&grid[xx][yy-1]=='1')
            {
                q.push(xx*m+yy-1);
                grid[xx][yy-1]='0';
            }
        }
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: