Number of Islands

salahelhossiny

SalahElhossiny

Posted on August 23, 2022

Number of Islands

Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return 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.

class Solution(object):
    def numIslands(self, grid):
        """
        :type grid: List[List[str]]
        :rtype: int
        """

        if not grid: 
            return 0

        rows, cols = len(grid), len(grid[0])

        islands = 0
        visited = set()

        def bfs(r, c):
            q = collections.deque()
            visited.add((r, c))
            q.append((r, c))

            while q: 
                row, col = q.pop()
                directions = [
                    [1, 0], [-1, 0],
                    [0, 1], [0, -1]
                ]
                for dr, dc in directions: 
                    if(
                        (r + dr) in range(rows) 
                        and (c + dc) in range(cols)
                        and grid[r+dr][c+dc] == "1" 
                        and (r+dr, c+dc) not in visited

                    ):
                        visited.add((r+dr, c+dc))
                        q.append((r+dr, c+dc))
                        bfs(r+dr, c+dc)



        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == "1" and (r, c) not in visited:
                    bfs(r, c)
                    islands += 1


        return islands 







Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
salahelhossiny
SalahElhossiny

Posted on August 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Distribute Candies
python Distribute Candies

May 13, 2023

Third Maximum Number
python Third Maximum Number

August 30, 2022

Max Rotate Function
python Max Rotate Function

August 23, 2022

Number of Islands
python Number of Islands

August 23, 2022