Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Capture the enclosed regions

Medium · Target 20 minutes · Graphs · Type asked atGoogleAmazon

A board is a grid of 'X' and 'O' cells, given as a list of equal-length strings. A region is a maximal group of 'O' cells connected through shared sides. A region is captured if none of its cells lies on the border of the board: every captured cell becomes 'X'. Regions with at least one cell on the border are left as they are. Return the board after capturing.

Examples

InputOutputWhy
board = ["XXXX","XOOX","XXOX","XOXX"]["XXXX","XXXX","XXXX","XOXX"]The three O cells in the middle are enclosed. The O in the bottom row is on the border.
board = ["XXXXX","XOOOX","XOXOO","XOOOX","XXXXX"]["XXXXX","XOOOX","XOXOO","XOOOX","XXXXX"]Unchanged. The ring of O cells leaks to the border at (2, 4), so the whole ring survives.
board = ["O"]["O"]A single cell is on the border.

Constraints

  • 1 ≤ rows, cols ≤ 200
  • Every cell is 'X' or 'O'

Hints

Hint 1

Checking each region for a border cell works, but it is easier to ask the opposite question: which O cells are connected to the border?

Hint 2

Start a flood fill from every O cell on the border, marking everything it reaches as safe.

Hint 3

Afterwards every O cell that is not safe is enclosed: turn it into X.

Where people lose marks

  • Capturing a region as soon as one of its cells is found to be interior, before checking whether another of its cells reaches the border.
  • Starting fills only from the corners or from two of the four edges.
  • Recursing on a 200 × 200 board of O cells: 40,000 frames deep. Use an explicit stack.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.