Parking Lot Puddles

Easydepth-first searchAlso known as Number of Islands

After a storm, a drone photographs a parking lot from above and splits the picture into a grid of squares. Each square is marked 1 if it is under water and 0 if it is dry. The maintenance crew sends one person with a squeegee to each puddle, so they need to know how many separate puddles there are.

Water squares that share an edge belong to the same puddle. Water squares that only touch at a corner do not: the crew has found that water does not flow across those diagonal cracks.

Your task

Write countPuddles(lot). lot is a grid of 0s and 1s. Return the number of puddles: groups of 1s joined up, down, left or right.

A grid with no rows, or with no 1s, has 0 puddles.

countPuddles(lot: int[][]) → int

Examples

Example 1
Input
lot = [[1, 1, 0, 0], [0, 1, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0]]
Output
3
Why

The three 1s in the top-left are one puddle. The two 1s on the right edge are a second. The lone 1 in the bottom-left corner is a third. Total 3.

Example 2
Input
lot = [[1, 0, 1], [0, 1, 0], [1, 0, 1]]
Output
5
Why

Every wet square touches the others only at corners, so each is its own puddle: 5.

Constraints

  • 0 ≤ rows ≤ 20
  • 1 ≤ cols ≤ 20 when rows ≥ 1
  • lot[r][c] is 0 or 1
Start with brute force

A tempting shortcut is to count a wet square as "the start of a new puddle" when the square above it and the square to its left are both dry. It looks right on blobs, but a U-shaped puddle has two tops, so it gets counted twice. The rule only sees two neighbors, while a puddle can wind around in any direction.

The safe slow version labels every wet square with its own puddle number, then repeatedly sweeps the grid, giving neighbors the smaller of their two labels until nothing changes, then counts distinct labels. That can take many full sweeps. A search from each new puddle finishes in one pass over the grid.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code