Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Surrounded Regions in Python
The Surrounded Regions problem involves capturing all regions of 'O' that are completely surrounded by 'X' on a 2D board. A region is considered surrounded if all 'O' cells are enclosed by 'X' cells and cannot reach the board's border.
Problem Understanding
Given a 2D board with 'X' and 'O' characters, we need to capture surrounded regions by flipping all 'O' to 'X'. However, 'O' cells connected to the border should remain unchanged ?
| Input Board | Output Board | ||||||||||||||||||||||||||||||||
|
|
Algorithm
The solution uses a reverse approach by identifying 'O' cells that should NOT be captured ?
- Mark all border 'O' cells and their connected 'O' cells as safe (using '1')
- Convert remaining 'O' cells to 'X' (these are surrounded)
- Convert safe cells ('1') back to 'O'
Implementation
class Solution:
def solve(self, board):
if not board:
return board
rows, cols = len(board), len(board[0])
# Check border cells and mark connected 'O' cells as safe
for i in range(rows):
if board[i][0] == 'O':
self.mark_safe(board, i, 0)
if board[i][cols-1] == 'O':
self.mark_safe(board, i, cols-1)
for j in range(cols):
if board[0][j] == 'O':
self.mark_safe(board, 0, j)
if board[rows-1][j] == 'O':
self.mark_safe(board, rows-1, j)
# Convert surrounded 'O' to 'X' and safe cells back to 'O'
for i in range(rows):
for j in range(cols):
if board[i][j] == 'O':
board[i][j] = 'X'
elif board[i][j] == '1':
board[i][j] = 'O'
return board
def mark_safe(self, board, i, j):
# Boundary checks
if (i < 0 or j < 0 or i >= len(board) or
j >= len(board[0]) or board[i][j] != 'O'):
return
# Mark as safe
board[i][j] = '1'
# Recursively mark connected cells
self.mark_safe(board, i+1, j)
self.mark_safe(board, i-1, j)
self.mark_safe(board, i, j+1)
self.mark_safe(board, i, j-1)
# Test the solution
board = [
["X","X","X","X"],
["X","O","O","X"],
["X","X","O","X"],
["X","O","X","X"]
]
solution = Solution()
result = solution.solve(board)
print("Result:")
for row in result:
print(row)
Result: ['X', 'X', 'X', 'X'] ['X', 'X', 'X', 'X'] ['X', 'X', 'X', 'X'] ['X', 'O', 'X', 'X']
How It Works
The algorithm uses depth-first search (DFS) to identify safe regions ?
- Border Scanning: Check all four borders for 'O' cells
- DFS Marking: Mark connected 'O' cells as safe using '1'
- Final Conversion: Surrounded 'O' ? 'X', Safe '1' ? 'O'
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(m × n) | Visit each cell at most once |
| Space | O(m × n) | Recursion stack in worst case |
Conclusion
The surrounded regions problem is solved efficiently using DFS to mark safe border-connected regions. Only truly surrounded 'O' regions are captured and converted to 'X'.
