Wednesday, November 16, 2016

Number of Islands -- LeetCode 200

[Question]
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
[Analysis]
Scanning through each position in the grid, if there is an '1', use BFS and find all '1' in this island. Then find another '1' for another island. The time complexity is O(MxN). 
Using DFS is also good and easier to implement. 
[Solution]
//
//--- BFS ---
//
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;
        
        int m=grid.size(), n=grid[0].size();
        int count=0;
        
        auto expand=[&grid, m, n](int x, int y) {
            queue<pair<int,int>> que;
            vector<pair<int,int>> dir = {{0,1}, {1,0},{0,-1},{-1,0}};
            
            que.push({x,y}); grid[x][y]=0;
            while (!que.empty()) {
                auto loc = que.front();
                que.pop();
                
                for (auto d: dir) {
                    int nx=loc.first+d.first, ny=loc.second+d.second;
                    if (nx>=0 &&nx<m && ny>=0 && ny<n && grid[nx][ny]=='1') {
                        que.push({nx,ny}); grid[nx][ny]=0;
                    }
                }
            }
        };
        
        for (int i=0; i<m; i++) 
            for (int j=0; j<n; j++) {
                if (grid[i][j]=='1') {
                    expand(i, j);
                    count++;
                }
            }
        return count;
    }
};

//
//--- DFS ---
//
class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;
        
        int m=grid.size(), n=grid[0].size();
        function<int(int,int)> dfs = [&] (int i, int j) {
            if (i<0||i>=m||j<0 || j>=n || grid[i][j]=='0') return 0;
            grid[i][j]='0';
            dfs(i+1,j); dfs(i-1,j); dfs(i,j+1); dfs(i,j-1);
            return 1;
        };
        
        int count=0;
        for(int i=0; i<m; i++) 
            for (int j=0; j<n; j++)
                count+= dfs(i, j);
                
        return count;
    }
};

No comments:

Post a Comment