leetcode-Number of Islands

Difficulty: Medium

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

class Solution {
    int col;
    int raw;
    void helper(vector<bool> &vis,vector<vector<char> > &grid,int i,int j){
        if(i>=raw||i<0||j>=col||j<0||grid[i][j]=='0'||vis[i*col+j]==true)
            return ;
        vis[i*col+j]=true;    
        helper(vis,grid,i+1,j);
        helper(vis,grid,i-1,j);
        helper(vis,grid,i,j+1);
        helper(vis,grid,i,j-1);
    }
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty())
            return 0;
        col=grid[0].size();
        raw=grid.size();
        int count=0;
        vector<bool> vis(col*raw);
        fill(vis.begin(),vis.end(),false);
        for(int i=0;i<raw;++i)
            for(int j=0;j<col;++j)
                if(grid[i][j]=='1'&&vis[i*col+j]==false){
                    helper(vis,grid,i,j);
                    ++count;
                }
        return count;        
    }
};

你可能感兴趣的:(leetcode-Number of Islands)