Skip to content

[200] Number of Islands

https://leetcode.com/problems/number-of-islands/description/

  • algorithms
  • Medium (38.83%)
  • Source Code: 200.number-of-islands.py
  • Total Accepted: 332.7K
  • Total Submissions: 811.6K
  • Testcase Example: '[["1","1","1","1","0"],["1","1","0","1","0"],["1","1","0","0","0"],["0","0","0","0","0"]]'

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:

Input: 11110 11010 11000 00000

Output: 1

Example 2:

Input: 11000 11000 00100 00011

Output: 3

python
class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """
        if not grid or not grid[0]: return 0
        m, n = len(grid), len(grid[0])

        visited = [[0] * n] * m # this is WRONG!!!
        visited = [[0 for c in range(n)] for r in range(m)]
        count = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1' and not visited[i][j]:
                    count += 1
                    self.BFS(i, j, m, n, visited, grid)
        return count


    def BFS(self, i, j, m, n, visited, grid):
        if 0 <= i < m and 0 <= j < n and grid[i][j] == '1' and not visited[i][j]:
            visited[i][j] = 1
            dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
            for k in range(4):
                self.BFS(i+dx[k], j+dy[k], m, n, visited, grid)
#
#
# if __name__ == '__main__':
#     grid = [['0', '1', '0'],
#             ['1', '0', '1'],
#             ['0', '1', '0']]
#
#     s = Solution()
#     c = s.numIslands(grid)
#     print(c)

Last updated: