Skip to main content

Surrounded Regions

Given a matrix of 'X' and 'O' characters Capture (flip to 'X') all regions that are completely surrounded by 'X' A region is NOT surrounded if it touches the border Return the modified board Example: [["X","X","X"],["X","O","X"],["X","X","X"]] => [["X","X","X"],["X","X","X"],["X","X","X"]]

Surrounded Regions is a traversal problem: the hard part is modeling the state you visit. Interviewers love it because it reveals your traversal modeling and your edge-case discipline. Once your traversal structure is solid, you can reuse it across dozens of problems.

Examples

You write

solve(board: List[List[str]])

  1. Example 1

    Input
    board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
    returns
    [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
  2. Example 2

    Input
    board = [["X"]]
    returns
    [["X"]]

The pattern behind it

Arrays & Hashing

I reach for it when

  • You catch yourself scanning the array again for every element.
  • The problem asks about duplicates, pairs, counts or groups.

Say this before you type. Say what the key is and what the value remembers, before you write the loop.

All 127 Arrays & Hashing problems

BFS & DFS

I reach for it when

  • You walk a grid, a graph or a tree and visit each cell once.
  • The word shortest appears and every step costs the same.

Say this before you type. Say why breadth or depth fits, and exactly when a cell counts as visited.

All 52 BFS & DFS problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Capture Surrounded Regionsmedium