LeetCode 200. Number of Islands

Description

https://leetcode.com/problems/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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

Explanation

if encounter ‘1’, an island found, use dfs to visit all its lands, and mark to “0”. Once the process finished. The next encountered ‘1’ suggests another island found.

Python Solution

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        count = 0
        
        for i in range(0, len(grid)):
            for j in range(0, len(grid[0])):

                if grid[i][j] == '1':
                    self.island_helper(grid, i, j)
                    count += 1
                                
        return count
        
    def island_helper(self, grid, i, j):
        if i < 0 or i > len(grid) - 1:
            return
        
        if j < 0 or j > len(grid[0]) -1:
            return
        
        if grid[i][j] == '0':
            return
        
        grid[i][j] = '0'

        self.island_helper(grid, i + 1, j)
        self.island_helper(grid, i - 1, j)
        self.island_helper(grid, i, j + 1)
        self.island_helper(grid, i, j - 1)
  • Time complexity: O(N).
  • Space complexity: O(N).

2 Thoughts to “LeetCode 200. Number of Islands”

Leave a Reply

Your email address will not be published. Required fields are marked *