> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Surrounded Regions Python Solution with Tests

> Tested Python solution for LeetCode 130 with 14 pytest cases. Generate a practice environment with lcpy.

LeetCode 130, Medium. Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix. [View on LeetCode](https://leetcode.com/problems/surrounded-regions/description/).

Generate this problem as a practice environment: tested reference solution, 14 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 130   # by problem number
lcpy gen -s surrounded_regions   # by problem name
```

## 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](https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg)

```
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: Notice that an 'O' should not be flipped if it is on the border of the board.
```

```
Input: board = [["X"]]
Output: [["X"]]
```

### 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](https://github.com/wislertt/leetcode-py/blob/main/leetcode/surrounded_regions/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/surrounded_regions/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from collections import deque


class Solution:
    # Time: O(m * n)
    # Space: O(m * n) for the border-connected queue in the worst case
    def solve(self, board: list[list[str]]) -> None:
        if not board or not board[0]:
            return
        m, n = len(board), len(board[0])
        queue: deque[tuple[int, int]] = deque()

        def enqueue(i: int, j: int) -> None:
            if board[i][j] == "O":
                board[i][j] = "#"
                queue.append((i, j))

        # Seed from all border cells
        for i in range(m):
            enqueue(i, 0)
            enqueue(i, n - 1)
        for j in range(n):
            enqueue(0, j)
            enqueue(m - 1, j)

        # BFS: mark every 'O' reachable from a border (cannot be captured)
        while queue:
            i, j = queue.popleft()
            for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                ni, nj = i + di, j + dj
                if 0 <= ni < m and 0 <= nj < n and board[ni][nj] == "O":
                    board[ni][nj] = "#"
                    queue.append((ni, nj))

        # '#' = safe border-connected 'O'; everything else enclosed gets captured
        for i in range(m):
            for j in range(n):
                board[i][j] = "O" if board[i][j] == "#" else "X"
```

## Complexity

| Time      | Space                                                      |
| --------- | ---------------------------------------------------------- |
| O(m \* n) | O(m \* n) for the border-connected queue in the worst case |

## Tags

[NeetCode 150](/catalog/neetcode-150), [NeetCode 250](/catalog/neetcode-250), [NeetCode All](/catalog/neetcode).
