Number of Islands

  22 Jun 2019

By Wen Xu

leetcode algorithm depth first search

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

Example 1:

Input: 11110 11010 11000 00000

Output: 1 Example 2:

Input: 11000 11000 00100 00011

Output: 3

Solution

We can use DFS to change all connected 1’s to X, and count groups of connected 1’s.

Below is my python implementation

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        count = 0
        m = len(grid)
        if m == 0:
            return 0
        n = len(grid[0])
        
        def neighbors(x:int, y:int)->List[List[int]]:
            ans = []
            if x + 1 < m and grid[x + 1][y] == '1':
                ans.append([x + 1, y])
            if x - 1 >= 0 and grid[x - 1][y] == '1':
                ans.append([x - 1, y])
            if y + 1 < n and grid[x][y + 1] == '1':
                ans.append([x, y + 1])
            if y - 1 >= 0 and grid[x][y - 1] == '1':
                ans.append([x, y - 1])
            return ans
        
        def dfs(i:int, j:int)->None: #mark 1's with X. When finish on island, add count by 1
            grid[i][j] = 'X'
            for neighbor in neighbors(i, j):
                x, y = neighbor
                dfs(x, y)
            return
        
        
        for i in range(m):
            for j in range(n):
                if grid[i][j] == '1':
                    dfs(i, j)
                    count += 1
        return count
				
				
comments powered by Disqus