DEV Community

SalahElhossiny
SalahElhossiny

Posted on • Edited on

1 1

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

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay