Parking Lot Puddles

Easydepth-first searchAlso known as Number of Islands

After a storm, a drone photographs a parking lot and splits the picture into a grid: 1 for a square under water, 0 for dry. The crew sends one person with a squeegee to each puddle, so they need the number of separate puddles.

Water squares that share an edge are the same puddle. Squares that touch only at a corner are not: 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 on the right edge a second, and the lone 1 in the bottom-left corner a third.

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.

Constraints

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

A tempting shortcut: count a wet square as a new puddle when the squares above and to its left are both dry. A U-shaped puddle has two tops, so it gets counted twice. The rule sees two neighbors, but a puddle can wind in any direction.

The safe slow version gives every wet square its own label, then sweeps the grid repeatedly, giving neighbors the smaller of their labels until nothing changes, and counts distinct labels. That can take many sweeps. A search from each new puddle needs one pass.

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