Problem statement

https://binarysearch.com/problems/Number-of-Islands/

Solution

Equal to Leetcode 0200 Number of Islands

Complexity

It is O(mn) for time and space.

Code

class Solution:
    def solve(self, grid):
        m, n, cnt = len(grid), len(grid[0]), 0
        
        def dfs(i, j):
            if not 0 <= i < m or not 0 <= j < n or grid[i][j] != 1:
                return
            grid[i][j] = -1
            for x, y in [[i+1,j],[i-1,j],[i,j-1],[i,j+1]]:
                dfs(x, y)
        
        for i, j in product(range(m), range(n)):
            if grid[i][j] == 1:
                dfs(i, j)
                cnt += 1
                
        return cnt