Leetcode 200. Number of Islands

Lintcode 433. Number of Islands

Posted by Olivia Liu on August 15, 2019 | 阅读:

Description

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.

Answer

Iterate each point of the given grid. If a point is land, using bfs to find all the adjacent '1' s recursively. Mark the adjacent '1's as '0' in case of duplication. Count how many times does '1' appears in iterations.

Code

C++

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if(grid.size() == 0 || grid[0].size() == 0) return 0;
        int n = grid.size(), m = grid[0].size();
        int cnt = 0;
        for(int i = 0; i < n; ++i)
        {
            for(int j = 0; j < m; ++j)
            {
                if(grid[i][j] == '1')
                {
                    bfs(grid, i, j);
                    ++cnt;
                }
            }
        }
        return cnt;
    }
    
    void bfs(vector<vector<char>> &grid, int row, int col)
    {
        if(row < 0 || row >= grid.size() || col < 0 || col >= grid[0].size() || grid[row][col] != '1') return;
        grid[row][col] = '0';
        bfs(grid, row - 1, col);
        bfs(grid, row + 1, col);
        bfs(grid, row, col - 1);
        bfs(grid, row, col + 1);
    }
};