DEV Community

SalahElhossiny
SalahElhossiny

Posted on • Edited on

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

Top comments (0)