Number of Closed Islands — Boundary DFS + Count

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

Count islands of 0 fully surrounded by 1. (Here 0=land, 1=water — reversed from standard.)


Approach

  1. DFS from all border 0s, marking them as 1 (water)
  2. Count remaining connected 0-components

Time: O(mn) | Space: O(mn)


Solutions

Python

class Solution:
    def closedIsland(self, grid: list[list[int]]) -> int:
        R,C=len(grid),len(grid[0])
        def dfs(r,c):
            if not(0<=r<R and 0<=c<C) or grid[r][c]!=0: return
            grid[r][c]=1
            for dr,dc in[(1,0),(-1,0),(0,1),(0,-1)]: dfs(r+dr,c+dc)
        for r in range(R): dfs(r,0); dfs(r,C-1)
        for c in range(C): dfs(0,c); dfs(R-1,c)
        count=0
        for r in range(R):
            for c in range(C):
                if grid[r][c]==0: dfs(r,c); count+=1
        return count

Complexity

  • Time: O(mn) | Space: O(mn)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro