CodingNodes / Graphs / Surrounded Regions System design Space play · ←→ step · R restart

Problem

A board is a grid of "X" and "O".

A group of connected "O" cells (connected up, down, left or right) is surrounded when none of its cells is on the border of the board and none of them can reach the border through other O cells.

Change every surrounded group to "X", in place. Groups that touch the border, directly or through other O cells, stay as they are. The method returns nothing.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • board[r][c] is "X" or "O"

Examples: pick one to animate

Solutions

TimeO(rows · cols) SpaceO(rows · cols)

Time: Each cell is scanned a constant number of times, and each O is marked, pushed and popped at most once with 4 neighbor checks.

Space: In the worst case (a board of O's) the stack holds O(rows · cols) cells. An explicit stack avoids deep recursion.

Don't search for surrounded regions; search for the ones that escape. Every O on the border is safe, and so is every O connected to it. Flood from all border O's at once with a stack, writing S on each safe cell. Then one final pass: leftover O becomes X, and S goes back to O.