MediumNo. 0130
Surrounded Regions — LeetCode 130 Python Solution
- Pattern
- Union-Find
- Topics
- Depth-First Search, Breadth-First Search, Union Find, Array, Matrix
- On study lists
- NeetCode 150 and Top Interview 150
- Reading time
- 4 min
- Source
- leetcode.com
The 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.
Python solution
class Solution:
def solve(self, board: List[List[str]]) -> None:
def dfs(i: int, j: int):
if not (0 <= i < m and 0 <= j < n and board[i][j] == "O"):
return
board[i][j] = "."
for a, b in pairwise((-1, 0, 1, 0, -1)):
dfs(i + a, j + b)
m, n = len(board), len(board[0])
for i in range(m):
dfs(i, 0)
dfs(i, n - 1)
for j in range(n):
dfs(0, j)
dfs(m - 1, j)
for i in range(m):
for j in range(n):
if board[i][j] == ".":
board[i][j] = "O"
elif board[i][j] == "O":
board[i][j] = "X"Complexity
- Time
- O(m × n)
- Space · auxiliary
- O(m × n)
Pattern: Union-Find
Merge groups and ask whether two things are connected, both in near-constant time. LeetCode 130. Surrounded Regions is filed here because LeetCode tags it Union Find, which is the vocabulary this hub collects.
The union-find guide has the Python template for the pattern and the 83 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0200 | Number of Islands | Medium |
| 0695 | Max Area of Island | Medium |
| 0827 | Making A Large Island | Hard |
| 1020 | Number of Enclaves | Medium |
| 1254 | Number of Closed Islands | Medium |
| 1267 | Count Servers that Communicate | Medium |
Frequently asked questions
- How hard is LeetCode 130. Surrounded Regions?
LeetCode 130. Surrounded Regions is rated Medium on LeetCode.
- What is the time complexity of LeetCode 130. Surrounded Regions?
The Python solution on this page runs in O(m × n).
- What is the space complexity of LeetCode 130. Surrounded Regions?
The Python solution on this page uses O(m × n) auxiliary space.
- What topics does LeetCode 130. Surrounded Regions cover?
LeetCode 130. Surrounded Regions is tagged Depth-First Search, Breadth-First Search, Union Find, Array and Matrix on LeetCode.