200. 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

Analysis

This problem is typical BFS and DFS, either approach can solve it. The idea is pretty straightforward. 

  • Loop the grid, find a '1', the number of island plus 1.
  • Do BFS(DFS) to search the adjacent area and set it to '0', indicating this position already visited.
  • Return the number of islands.

Time complexity is O(m * n). Space complexity is O(1).

BFS solution

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()){
            return 0;
        }
        int cnt = 0;
        int row = grid.size();
        int col = grid[0].size();
        vector<pair<int, int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                if(grid[i][j] == '1'){
                    cnt++;
                    grid[i][j] = '0';
                    queue<pair<int, int>> que;
                    que.push({i, j});
                    while(!que.empty()){
                        pair<int, int> cur = que.front();
                        que.pop();
                        for(auto dir : dirs){
                            int x = cur.first + dir.first;
                            int y = cur.second + dir.second;
                            if(x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == '1'){
                                que.push({x, y});
                                grid[x][y] = '0';
                            }
                        }
                    }
                }
            }
        }
        return cnt;
    }
};

DFS solution

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.empty()){
            return 0;
        }
        int cnt = 0;
        for(int i = 0; i < grid.size(); i++){
            for(int j = 0; j < grid[0].size(); j++){
                if(grid[i][j] == '1'){
                    grid[i][j] = '0';
                    cnt++;
                    island_search(grid, i, j);
                }
            }
        }
        return cnt;
    }
private:
    void island_search(vector<vector<char>>& grid, int i, int j){
        vector<pair<int,int>> dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for(auto dir : dirs){
            int x = dir.first + i;
            int y = dir.second + j;
            if(x >= 0 && x < grid.size() && y >= 0 && y < grid[0].size() && grid[x][y] == '1'){
                grid[x][y] = '0';
                island_search(grid, x, y);
            }
        }
        return;
    }
};

 

posted @ 2017-06-08 08:17  蓝色地中海  阅读(123)  评论(0编辑  收藏  举报