← Whiteboard questions

Surrounded Regions

Fill the ponds that are cut off from the edge

DSA, Medium, Graphs

Which structure or algorithm, and what does it cost.

A garden plan is a list of strings of equal length. ~ is pond water and # is stone. Water cells touch by a side: up, down, left or right. A pond is a group of touching water cells. A pond is open if any of its cells is on the edge of the plan, and sealed otherwise. Write fill_sealed_ponds(grid). It returns a new plan where every cell of a sealed pond is #. Open ponds and stone stay as they are. Do not change grid.

Examples

Input grid = ["~~#~~~", "~#~#~~", "~#~#~#", "~~#~~~", "~~~~~~"]
Output ["~~#~~~", "~###~~", "~###~#", "~~#~~~", "~~~~~~"]
Why the two water cells in the middle column touch each other and nothing else, so they are filled. Every other water cell reaches the edge.
Input grid = ["###", "#~#", "###"]
Output ["###", "###", "###"]
Why the single water cell is not on the edge and has no water neighbour, so it is sealed.
Input grid = ["~~", "~~"]
Output ["~~", "~~"]
Why every cell is on the edge, so nothing is sealed.

Constraints

Your answer must contain

Target Aim for O(R * C) time and memory, where R is the number of rows and C the number of columns.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

Which water cells can you be sure are not sealed? Think about the cells on the edge of the plan.

Hint 2 the approach

Instead of testing each pond, mark the water that is open. A water cell is open if it is on the edge or touches open water.

Hint 3 the key step

Start one search from every water cell on the edge and spread through touching water. Keep the cells you reach as water and turn every other cell into stone.

Walkthrough

Full walkthrough brute force to best

Brute force

For every water cell, start a search through touching water and see whether it reaches a cell on the edge. A search can visit every cell, so this costs O((R * C)^2) time. Searching again for each cell of a big pond repeats the same work.

Best method

Find the open water instead of the sealed water. A water cell on the edge is open, and so is any water cell that touches open water. Put all water cells on the edge in a queue and mark them open. Take a cell off the queue, and for each side neighbour that is water and not yet marked, mark it open and queue it. When the queue is empty, every open water cell is marked, and every other water cell is in a sealed pond. Build the new plan row by row: a cell is water if it is marked open, and stone otherwise. Stone stays stone, and sealed water becomes stone.

Hand trace

Example 1: the 16 water cells on the edge start the queue: (0,0), (0,1), (0,3), (0,4), (0,5), (1,0), (1,5), (2,0), (3,0), (3,5) and the whole bottom row (4,0) to (4,5). The search then reaches (1,4), (2,4), (3,1), (3,3) and (3,4) through touching water, so 21 of the 23 water cells are open. The cells (1,2) and (2,2) are never reached. They become stone, and the new plan is ["~~#~~~", "~###~~", "~###~#", "~~#~~~", "~~~~~~"].

Code

from collections import deque
def fill_sealed_ponds(grid):
    rows, cols = len(grid), len(grid[0])
    open_water = set()
    todo = deque()
    for r in range(rows):
        for c in range(cols):
            if (r in (0, rows - 1) or c in (0, cols - 1)) and grid[r][c] == '~':
                open_water.add((r, c))
                todo.append((r, c))
    while todo:
        r, c = todo.popleft()
        for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == '~' and (nr, nc) not in open_water:
                open_water.add((nr, nc))
                todo.append((nr, nc))
    return [''.join('~' if (r, c) in open_water else '#' for c in range(cols)) for r in range(rows)]

Time and memory

O(R * C) time and O(R * C) memory. Each water cell is marked and queued at most once, and looked at from four sides. The marked set, the queue and the new plan take up to R * C cells.

Common mistakes

  • Filling every water cell that is not on the edge. A pond that touches the edge can reach deep into the plan, and all of its cells stay water.
  • Treating one edge cell as the whole story. One edge cell keeps its entire pond open, so you must spread to touching water.
  • Trying to change the strings in place. A string cannot change in place, so build new rows.

Related problems

More Graphs problems
Surrounded Regions: hints, walkthrough and Python solution