InterviewPrepKit

Home / Coding / Graphs

Surrounded Regions

medium Original ↗
Solving tips
  • Invert the question: instead of 'is this region enclosed?', mark which 'O's are safe, i.e. reachable from a border 'O'; the complement is captured.
  • Flood-fill (DFS/BFS) from every border 'O' tagging reachable cells with a sentinel like 'S', then in a final sweep flip remaining 'O' to 'X' and revert 'S' back to 'O'; O(m*n).
  • Seeding from the border once avoids the O((m*n)^2) trap of testing each region separately.
  • Pitfall: remember to restore the sentinels to 'O', and on a 200x200 all-'O' grid recursive DFS can blow the stack so prefer BFS.

Problem

You’re given an m x n grid of characters, each 'X' or 'O'. A group of 'O's that are 4-directionally connected forms a region. A region is captured if it is completely surrounded by 'X' — meaning none of its cells lie on the border of the grid.

Flip every captured region’s 'O's to 'X', in place. Any region touching the outer edge survives untouched.

Examples

  • X X X X          X X X X
    X O O X    →     X X X X
    X X O X          X X X X
    X O X X          X O X X

    The middle region of three 'O's never touches the border, so it’s captured. The lone 'O' on the bottom row sits on the edge, so it stays.

  • O O          O O
    O O    →     O O

    Every 'O' touches the border → nothing is captured.

  • X X X          X X X
    X O X    →     X X X
    X X X          X X X

    A single enclosed 'O' is captured.

Constraints

  • 1 <= m, n <= 200, so up to 40,000 cells — the solution must be roughly linear in the number of cells.
  • Only 'X' and 'O' appear. Connectivity is 4-directional (up/down/left/right), not diagonal.

Think about it first

Hint 1 Deciding "is this region surrounded?" for each region separately is a lot of repeated work. Flip the question: which 'O's are safe? A region is safe exactly when at least one of its cells sits on the border.
Hint 2 Start from the border. Every 'O' on an edge — and everything reachable from it — is safe. Mark all of those first; whatever 'O's remain unmarked are, by definition, enclosed and should be flipped.
Hint 3 "Everything reachable from a border cell" is a flood fill: run DFS or BFS from each border 'O', tagging visited cells with a temporary marker. This is also a classic union-find problem — union every border-connected 'O' with a virtual "safe" node.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.