TRT
Sign in
mediumAdvancedLeetCode#search from the border

Surrounded regions

Capture regions of O cells that don't touch the border, by first marking every O reachable from the border.

The Runtime Theory Team1 min read
Taught inCycles and connected componentsPro — members onlyOne walk over a graph can split it into connected pieces, tell whether it is a tree, and find cycles. Directed graphs need one extra idea: remembering which vertices are on the current path.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inboard = [[X,X,X,X],[X,O,O,X],[X,X,O,X],[X,O,X,X]]

out[[X,X,X,X],[X,X,X,X],[X,X,X,X],[X,O,X,X]]

inboard = [[X]]

out[[X]]

inboard = [[O, O], [O, O]]

outunchanged

In a board of X and O, flip every O that belongs to a region not connected to the border into X. O cells connected to the border stay.

Before you code

Deciding for each region whether it touches the border is awkward. The complement is easy: flood from every border O, and whatever the flood reaches is safe.

Hints

  1. DFS or BFS from each O on the border, marking reached cells as safe (for example, change them to S).
  2. Scan the board: remaining O become X, and S become O again.
  3. Each cell is visited a constant number of times.

Production & complexity notes

When solving Surrounded regions on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Cycles and connected components to reinforce the underlying pattern.

What it practices

Separating components by whether they touch a boundary, from Cycles and connected components.

Not started

Sign in to save your learning progress.

Sign in to save