Surrounded Regions
Detailed guide and Python implementation for the 'Surrounded Regions' problem.
1. Concept Overview
The 'Surrounded Regions' problem is a key challenge in the Graphs section.
This implementation focuses on easy-level logic in Python.
We prioritize technical accuracy and code readability in our provided solutions.
2. Real-World Applications
3. Visual Intuition
Visualizing the logic flow for Surrounded Regions.
4. Prerequisites
5. Step-by-Step Thinking
1. Understand the problem
Read the problem statement for Surrounded Regions carefully.
2. Formulate brute force
Draft a simple iterative solution.
3. Identify inefficiency
Look for redundant calculations.
4. Optimize search path
Use hashing or sorting to speed up the process.
5. Final Implementation
Clean up the code for production standards.
Problem Statement
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.
- •m == len(board)
- •n == len(board[i])
- •1 <= m, n <= 200
- •board[i][j] is 'X' or 'O'
Examples
board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
[["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
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?
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.
Interview Insights & Variations
Complexity Analysis Breakdown
Why Time: Directly evaluates all possibilities.
Why Space: Uses standard local memory.
Why Time: Optimized paths reduce total operations.
Why Space: May trade memory for speed.
Optimized Solution Python Code
Optimized Solution Python Code
def solve_opt(board):
ROWS, COLS = len(board), len(board[0])
def capture(r, c):
if r < 0 or r == ROWS or c < 0 or c == COLS or board[r][c] != "O": return
board[r][c] = "T"
capture(r + 1, c); capture(r - 1, c); capture(r, c + 1); capture(r, c - 1)
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == "O" and (r in [0, ROWS - 1] or c in [0, COLS - 1]):
capture(r, c)
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == "O": board[r][c] = "X"
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == "T": board[r][c] = "O"Brute Force Code (Spoiler Guarded)
Brute Force Code (Spoiler Guarded)
def solve_brute(board):
ROWS, COLS = len(board), len(board[0])
def dfs(r, c, visited):
if r < 0 or r == ROWS or c < 0 or c == COLS: return False
if board[r][c] == 'X' or (r, c) in visited: return True
visited.add((r, c))
return dfs(r+1, c, visited) and dfs(r-1, c, visited) and dfs(r, c+1, visited) and dfs(r, c-1, visited)
for r in range(ROWS):
for c in range(COLS):
if board[r][c] == 'O':
visited = set()
if dfs(r, c, visited):
for vr, vc in visited: board[vr][vc] = 'X'Algorithm Pattern Checklist
When dealing with Graphs data patterns.
Core Prerequisites
Revision Key Notes
Common Mistakes & Pitfalls
Related Questions
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.