#200

Number of Islands

Medium Connected components on a grid

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In a grid of '1' (land) and '0' (water), count islands — groups of land connected up/down/left/right.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many separate groups of land?

Why this works: each time you find new land, count one island and sink the whole island with DFS so it isn't counted again.

Example: 1 1 0 / 0 1 0 / 0 0 1

first island: top-left 3 cellssecond island: bottom-right cell → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Counting diagonal neighbours as connected.

Solve on LeetCode ↗
Complexity
  • Time: O(m·n).
  • Space: O(m·n) worst-case recursion.
Topic: Graphs
🎬 Episodes 74–85: video coming soon