Back to Practice Dashboard
Top 150 InterviewEasy

Surrounded Regions

Learn how to solve the 'Surrounded Regions' problem. This detailed resource details brute force and optimized approaches.

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?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

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

Open in Editor