Top 150 InterviewEasy

Surrounded Regions

Detailed guide and Python implementation for the 'Surrounded Regions' problem.

Problem Statement

Easy

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

Write a function solve(board: List[List[str]]) -> List[List[str]] that returns the modified board.

Constraints
  • m == len(board)
  • n == len(board[i])
  • 1 <= m, n <= 200
  • board[i][j] is 'X' or 'O'

Examples

Example 1
Input
board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
Output
[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
Explanation

Surrounded regions should not be on the border, which means any 'O' on the border of the board is not flipped to 'X'. Any 'O' that is connected to a border 'O' is also not flipped.

Need a Hint?
Consider using Graphs-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.