Fill the Landlocked Ponds

Medium · Graphs, BFS & DFS · about 20 min

A town map is a grid: 1 is water and 0 is land. Water cells that touch up, down, left or right belong to the same pond (diagonals do not join). A pond that has at least one cell on the edge of the map drains away to a river and is kept. Every other pond is landlocked, and the town fills it in: all of its cells become 0.

Return the map after all landlocked ponds are filled. You may change the input grid.

Example:

fill_landlocked_water([[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0]]) → [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0]]

Hints

  • Deciding pond by pond is fiddly. Ask instead: which water can be reached from the edge?
  • Start a search from every water cell in the first and last row and the first and last column, and mark all the water it reaches.
  • Finally, turn every unmarked water cell into land.

Learn the pattern first: the Graphs, BFS & DFS lesson.

More Graphs, BFS & DFS problems