download

Water spreads one cell a minute. When is every cell wet?

Algorithms~20 minReviewed 1 Nov 2026Free · No sign-in

Question

A pipe leaks in a warehouse. The floor plan is a grid of strings: "W" is a wet cell, "." is a dry cell and "#" is a wall. Every minute, water spreads from each wet cell to the dry cells next to it: up, down, left and right.

Write minutes_to_flood(grid). Return the number of minutes until no dry cell is left. If some dry cell can never get wet, return -1. A grid with no dry cells returns 0. Aim for O(rows × cols) time.

"PYTHON"
minutes_to_flood(["W...", ".#..", "...W"])  # 2
minutes_to_flood(["W.#.", "..#."])          # -1
minutes_to_flood(["W#", "#W"])              # 0
"CODE · PYTHON"
def minutes_to_flood(grid):
    ...
Show hints (3)
  1. "BOTH LEAKS AT ONCE"

    The first example has two wet cells, and both spread at the same time. What if every wet cell starts in the queue at minute 0, before the search begins?

  2. "WHICH SEARCH"

    Breadth-first search takes cells out of the queue in order of distance: all minute-1 cells before any minute-2 cell. Store the minute next to each cell you queue.

  3. "THE -1 CASE"

    Count the dry cells before you start. Mark a cell wet when you queue it, and subtract 1 from the count. If the count is not 0 at the end, return -1.

Show checked explanation

Run one breadth-first search that starts from every wet cell at minute 0. Each cell you take out wets its dry neighbours and queues them for the next minute. The last minute taken out is the answer. If a dry cell is never reached, return -1. Time is O(rows × cols).

"SOLUTION · PYTHON"
from collections import deque


def minutes_to_flood(grid):
    cells = {(r, c): ch for r, row in enumerate(grid)
             for c, ch in enumerate(row)}
    queue = deque((cell, 0) for cell, ch in cells.items() if ch == "W")
    dry, minute = sum(ch == "." for ch in cells.values()), 0
    while queue:
        (r, c), minute = queue.popleft()
        for cell in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
            if cells.get(cell) == ".":
                cells[cell] = "W"  # mark it now, so it is queued once
                dry -= 1
                queue.append((cell, minute + 1))
    return minute if dry == 0 else -1


for grid in (["W...", ".#..", "...W"], ["W.#.", "..#."], ["W#", "#W"]):
    print(minutes_to_flood(grid))
"OUTPUT"
2
-1
0

Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.

Walkthrough

Here is the first grid. Each dry cell shows the minute it gets wet:

rowcol 0col 1col 2col 3
0W122
11#21
2221W

The queue starts with both wet cells at minute 0. They wet 4 cells, which join the queue at minute 1. Those 4 wet the last 5 dry cells at minute 2. Nothing dry is left, so the answer is 2.

Why are the minutes right? The queue is first in, first out, so every minute-1 cell comes out before any minute-2 cell. So each cell gets wet from its nearest leak, and the last cell taken out has the largest minute. Putting every leak in the queue first is the whole trick.

Mark a cell wet when you queue it, not when you take it out. Then no cell is queued twice. Each cell is handled once and looks at 4 neighbours, so time and memory are O(rows × cols). cells.get returns None outside the grid, so you need no bounds checks.

In ["W.#.", "..#."] the right column sits behind a wall. The search ends with 2 dry cells left, so the answer is -1. In ["W#", "#W"] nothing is dry, so the answer is 0.

Common mistakes

  • Running a separate search from each leak and keeping the largest answer. From the top-left leak alone, the far cells are 4 steps away, so you get 4, not 2.
  • Simulating minute by minute and wetting cells in the same grid you scan. A cell wetted earlier in the scan spreads again that minute: ["W..."] gives 1 minute instead of 3.
  • Adding 1 after every round of the queue, including the last round, which wets nothing. The first grid then gives 3, and ["W#", "#W"] gives 1 instead of 0.
  • Forgetting the -1 check. For ["W.#.", "..#."] you return 2 and miss the 2 cells behind the wall.

Follow-up questions

  • "Why not depth-first search?" Depth-first search follows one path as deep as it can. The first time it reaches a cell is often not the shortest way, so it would have to revisit cells. A recursive version also fails on a long corridor: Python's recursion limit is 1000 by default (sys.getrecursionlimit()).
  • "Crossing some cells takes 2 minutes. What changes?" Now a step can cost 1 or 2 minutes, and plain breadth-first search can return the wrong time. Use Dijkstra's algorithm with heapq. Start with every leak in the heap at time 0, the same trick as before.

What a strong answer covers

Puts all leaks in the queue first, because they spread at the same time. Marks cells when queued, counts dry cells for the -1 case and handles a grid with nothing dry. States O(rows × cols) and why breadth-first search gives the right minutes.

Open in interactive practice deck →

Original OfferVibe question. Topic idea from Coding Interview Patterns (Alex Xu and Shaun Gunawardane, 2024); text, examples and code are our own.
© 2026 OfferVibe · Text CC BY-NC-SA 4.0 · code MITFree to share and adapt with credit, not for commercial use. Code samples are free for any use.