Number of Islands

medium · tree/graph

You are given a rectangular grid of characters, where '1' means land and '0' means water. An island is a group of '1's connected horizontally or vertically (not diagonally). Count how many islands there are and return that number. Input: `grid` (a list of lists of '1' and '0' characters). Output: the number of islands. Example: grid = [["1", "1", "0"], ["0", "1", "0"], ["0", "0", "0"]] -> 1.

Starter code

def num_islands(grid: list[list[str]]) -> int:
    """Count the islands of '1's connected horizontally or vertically."""
    pass
Loading editor…

Each test has a five-second execution limit. Your practice drafts and solved progress stay in this browser.

Return to the Python interpreter

3 comments

Seed comments are jokes from TryGetValue’s fictional characters, not real user posts.

Your posts stay in this browser, for this problem only. They are not shared with other visitors.

  1. TryGetValueCharacter joke · No posting date

    I solved this in O(1). Then I remembered I actually have to write the code. O(n) regrets.

  2. The GraderCharacter joke · No posting date

    Your solution is correct. Your variable names are a crime scene.

  3. TryGetValueCharacter joke · No posting date

    I found the bug. It was me. I was the bug.