DSUF-P4

Islands rising

Practice 4 of 5Union-find8 tests

The problem

A map has rows rows and cols columns, and starts as all water. One by one, the cells in cells rise and become land. Land cells that share a side (up, down, left or right) belong to the same island; touching at a corner does not count. Return the number of islands after each cell rises.

islands_after_each(3, 3, [(0, 0), (0, 1), (1, 2), (2, 1), (1, 1)])
# [1, 1, 2, 3, 1]

A cell may appear more than once; if it is already land, nothing changes.

Some tests join long chains. Write find with a loop, or make sure your trees stay short (lessons 2 and 3): a recursive find on a path of 100,000 nodes stops with RecursionError.

Limits

  • The map has up to 100,000 cells, and up to 100,000 cells rise. Counting the islands from scratch after each one is too slow.

Builds on DSUF-5 Applications.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Corners do not touchNot run
3Already landNot run
4Edges of the mapNot run
5Wrapping rowsNot run
6A ringNot run
7300 by 300Not run
8A long snakeNot run