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.

Idea

Depth search

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
  #      visited = set()
 
        N = len(grid)
        if not N:
            return 0
        M = len(grid[0])
        if not M:
            return 0
 
        def searchFromCell(i: int, j: int, island_id: int): 
            if grid[i][j] != "1":
                return
 
            grid[i][j] = island_id
            
            if i > 0:
                searchFromCell(i-1, j, island_id)
            if i < N - 1:
                searchFromCell(i+1, j, island_id)
            if j > 0:
                searchFromCell(i, j-1, island_id)
            if j < M - 1:
                searchFromCell(i, j+1, island_id)
 
        island_id = 1
        for i in range(len(grid)):
            for j in range(len(grid[0])):
                if grid[i][j] == "1":
                    island_id += 1
                    searchFromCell(i, j, island_id)
        
        return island_id - 1