Skip to main content
LeetCode 130, Medium. Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 14 parametrized pytest cases, and a playground notebook:

Problem

You are given an m x n matrix board containing letters 'X' and 'O', capture regions that are surrounded:
  • Connect: A cell is connected to adjacent cells horizontally or vertically.
  • Region: To form a region connect every 'O' cell.
  • Surround: A region is surrounded if none of the 'O' cells in the region are on the edge of the board. Such regions are completely enclosed by 'X' cells.
To capture a surrounded region, replace all 'O's with 'X's in-place within the original board. You do not need to return anything.

Examples

Example 1

Constraints

  • m == board.length
  • n == board[i].length
  • 1 <= m, n <= 200
  • board[i][j] is ‘X’ or ‘O’.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode 150, NeetCode 250, NeetCode All.
Last modified on August 25, 2026