Surrounded Regions

35 min · solve()

Picture white tiles inside a dark frame. A white patch sealed away from the frame gets painted dark; a white path that reaches the frame survives.

You're given a rectangular board made of "X" and "O" cells. An "O" region is captured when none of its cells connects to a border "O" through up, down, left, or right moves. Flip every captured region to "X", keep every border-connected region, and return the resulting board.

A few ground rules:

  • Diagonal cells don't connect.
  • One border connection protects the entire connected "O" region.
  • The returned board must keep the same rows and columns as the input.

Constraints

  • 1 <= board.length <= 200
  • 1 <= board[r].length <= 200
  • Every row has the same length.
  • board[r][c] is either "X" or "O".

Hints

Invert the question

Testing every interior region is expensive. Which "O" cells are guaranteed not to be captured, and where must every such region begin?

Start from the frame

Run a traversal from every border "O". Mark all "O" cells reachable from those starts as safe.

Resolve three states

After marking, unmarked "O" cells become "X". Marked safe cells become "O" again. Original "X" cells never move.

Follow-up

Can you prove that searching only from the border finds every region that must survive?

Visible cases

Examples

Example 1

ready
Input
board = [
  [
    "X",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "O",
    "O",
    "X"
  ],
  [
    "X",
    "X",
    "O",
    "X"
  ],
  [
    "X",
    "O",
    "X",
    "X"
  ]
]
Expected
[
  [
    "X",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "O",
    "X",
    "X"
  ]
]
Why
the enclosed three-cell region flips; the border O survives

Example 2

ready
Input
board = [
  [
    "O",
    "O",
    "O"
  ],
  [
    "O",
    "X",
    "O"
  ],
  [
    "O",
    "O",
    "O"
  ]
]
Expected
[
  [
    "O",
    "O",
    "O"
  ],
  [
    "O",
    "X",
    "O"
  ],
  [
    "O",
    "O",
    "O"
  ]
]
Why
every O belongs to a region touching the border

Example 3

ready
Input
board = [
  [
    "X",
    "O",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "O",
    "O",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "O",
    "X",
    "X"
  ],
  [
    "X",
    "O",
    "X",
    "O",
    "X"
  ],
  [
    "X",
    "X",
    "X",
    "X",
    "X"
  ]
]
Expected
[
  [
    "X",
    "O",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "O",
    "O",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "O",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "X",
    "X",
    "X"
  ],
  [
    "X",
    "X",
    "X",
    "X",
    "X"
  ]
]
Why
the top-connected path stays O while two isolated interior cells flip

Interview signal

Asked at

AmazonGoogle
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite