InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Graphs

Surrounded Regions

medium Original ↗ 00:00

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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug