number_of_islands

Solution

	
	"""
https://leetcode.com/problems/number-of-islands/description/

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.
"""

from typing import List

DIRECTIONS = [[0, 1], [0, -1], [-1, 0], [1, 0]]


def count(arr: List[List[int]]) -> int:
    ROWS, COLS = len(arr), len(arr[0])
    visited = set()
    islands = 0

    def inbounds(row, col):
        return row in range(ROWS) and col in range(COLS)

    def land(row, col):
        return arr[row][col] != "0"

    def seen(row, col):
        return (row, col) in visited

    def dfs(r, c):

        if not inbounds(r, c) or not land(r, c) or seen(r, c):
            return
        # element is inbounds, on land and not visited
        visited.add((r, c))

        for dx, dy in DIRECTIONS:
            dfs(r + dx, c + dy)

    for r in range(ROWS):
        for c in range(COLS):
            if land(r, c) and not seen(r, c):
                islands += 1
                dfs(r, c)
    return islands

	

Tests

	
	from publicmatt.leet.problems.number_of_islands import count


def test_single_island():
    arr = [
        ["1", "1", "1", "1", "0"],
        ["1", "1", "0", "1", "0"],
        ["1", "1", "0", "0", "0"],
        ["0", "0", "0", "0", "0"],
    ]
    assert count(arr) == 1


def test_multiple_island():
    grid = [
        ["1", "1", "0", "0", "0"],
        ["1", "1", "0", "0", "0"],
        ["0", "0", "1", "0", "0"],
        ["0", "0", "0", "1", "1"],
    ]
    assert count(grid) == 3


def test_no_island():
    grid = [
        ["0", "0", "0", "0", "0"],
        ["0", "0", "0", "0", "0"],
        ["0", "0", "0", "0", "0"],
        ["0", "0", "0", "0", "0"],
    ]
    assert count(grid) == 0

	
number_of_islands