Limited Time Offer:Up to 20% off Hello Interview Premium
Up to 20% off Hello Interview Premium 🎉
Hello Interview
Learn Code
Introduction
Overview
Container With Most Water
Two Sum (Sorted Array)
3-Sum
Triangle Numbers
Move Zeroes
Sort Colors
Trapping Rain Water
Overview
Maximum Sum of Subarrays of Size K
Max Points You Can Obtain From Cards
Max Sum of Distinct Subarrays Length k
Overview
Longest Substring Without Repeating Characters
Longest Repeating Character Replacement
Overview
Can Attend Meetings
Insert Interval
Non-Overlapping Intervals
Merge Intervals
Employee Free Time
Overview
Valid Parentheses
Decode String
Longest Valid Parentheses
Monotonic Stack
Daily Temperatures
Largest Rectangle in Histogram
Overview
Linked List Cycle
Palindrome Linked List
Remove Nth Node From End of List
Reorder List
Swap Nodes in Pairs
Overview
Apple Harvest (Koko Eating Bananas)
Search in Rotated Sorted Array
Split Array Largest Sum
Kth Smallest Element in a Sorted Matrix
Minimum Shipping Capacity
Overview
Kth Largest Element in an Array
K Closest Points to Origin
Find K Closest Elements
Merge K Sorted Lists
Median from Data Stream
Introduction
Fundamentals
Return Values
Maximum Depth of Binary Tree
Path Sum
Passing Values Down and Helper Functions
Validate Binary Search Tree
Calculate Tilt
Diameter of a Binary Tree
Path Sum II
Longest Univalue Path
Graphs Overview
Adjacency List
Copy Graph
Graph Valid Tree
Matrices
Flood Fill
Number of Islands
Surrounded Regions
Pacific Atlantic Water Flow
Introduction
Overview
Level Order Sum
Rightmost Node
Zigzag Level Order
Maximum Width of Binary Tree
Graphs Overview
Minimum Knight Moves
Rotting Oranges
01-Matrix
Bus Routes
Overview
Word Search
Solution Space Trees
Subsets
Generate Parentheses
Combination Sum
Palindrome Partitioning
N-Queens
Overview
Course Schedule
Course Schedule II
Shortest Path Algorithms
Network Delay Time
Cheapest Flights Within K Stops
Path With Minimum Effort
Find City with Fewest Reachable
Fundamentals
Solving a Question with Dynamic Programming
Counting Bits
Decode Ways
Unique Paths
Maximal Square
Longest Increasing Subsequence
Word Break
Maximum Profit in Job Scheduling
Paint House
Paint House II
Minimum Window Subsequence
Overview
Best Time to Buy and Sell Stock
Gas Station
Jump Game
Jump Game II
Partition Labels
Overview
Implement Trie Methods
Prefix Matching
Overview
Count Vowels in Substrings
Subarray Sum Equals K
Spiral Matrix
Rotate Image
Set Matrix Zeroes
Vote For New Content
Pricing
Sign in / Sign up
Search
⌘K
Pricing

Tutor

Depth-First Search

Surrounded Regions

medium

max (21)341224132;341225102;21365487109
Count: 10
abcValid triangle requires:a + b > c AND a + c > b AND b + c > a(every pair must sum to more than the third side)3511SOURCE23211SOURCE23UNREACHABLE$100$100$100$5000SRC123DST$100$100$1000SRC123DST01233141Threshold: 4Answer: 32 reachable01234231118Threshold: 2Answer: 01 reachable1102233321432263321
DESCRIPTION (inspired by Leetcode.com)

Given an m x n matrix grid containing only characters 'X' and 'O', modify grid to replace all regions of 'O' that are completey surrounded by 'X' with 'X'.

A region of 'O' is surrounded by 'X' if there is no adjacent path (cells that border each other in the N, W, E, S directions) consisting of only 'O' from anywhere inside that region to the border of the board.

Input:

grid = [
["X","X","X","X","O"],
["X","X","O","X","X"],
["X","X","O","X","O"],
["X","O","X","X","X"]
["X","O","X","X","X"]
]

Output:

[
["X","X","X","X","O"],
["X","X","X","X","X"],
["X","X","X","X","O"],
["X","O","X","X","X"],
["X","O","X","X","X"]
]

Explanation: The region of O's at grid[1][2] and grid[2][2] is completely surrounded, so we replace them with X's. All the other "O"s are connected to the border by a path of all "O"s, so we leave them as is.

Input:

grid = [
["O","O"],
["O","X"],
]

Output:

[
["O", "O"],
["O", "X"]
]

Explanation: All the "O"s are connected to the border.

Explanation

In order to solve this problem, we can first recognize that there are two types of "Os" in the grid, those that are reachable on a path of connected "O"s starting from the border of the grid, and those that are not.
XXXXOXXOXXXXOXOXOXXXXOXXX
The "Os" that are reachable from the border are highlighted in light blue, while the ones that aren't a highlighted in dark blue.
The "Os" that are reachable from the border are the ones that we want to keep, while the "Os" that are not reachable from the border are the ones that we want to change to "Xs".
In order for an "O" to be reachable from the border, it must be connected to an "O" that is on the border. This means that we can start from each cell in the border of the grid and use depth-first search to find all the "Os" that are reachable from the border of the grid (by following a path of connected "Os" in the N, E, S, W directions). Whenever we find an "O" that is reachable from the border, we can change its value to "S" to mark it as safe.
XXXXSXXOXXXXOXSXSXXXXSXXX
All the "Os" that are reachable from the border are marked with "S".
After marking them as safe, we can then iterate through each cell in the grid and change the "Os" that are not marked as safe to "Xs", while also changing the "safe" cells back to "Os".
XXXXOXXXXXXXXXOXOXXXXOXXX
The final grid.
Solution
Python
Language
class Solution:
def surrounded_regions(self, grid):
if not grid:
return grid
rows = len(grid)
cols = len(grid[0])
# recursive function to find all the "O"s that are reachable
# from the border and mark them as "S"
def dfs(x, y):
# return immediately if the cell is out of bounds or is not an "O
if x < 0 or y < 0 or x >= rows or y >= cols or grid[x][y] != 'O':
return
grid[x][y] = 'S'
# explore the neighboring cells
dfs(x + 1, y)
dfs(x - 1, y)
dfs(x, y + 1)
dfs(x, y - 1)
# initialize the dfs for the first and last column
for i in range(rows):
if grid[i][0] == 'O':
dfs(i, 0)
if grid[i][cols - 1] == 'O':
dfs(i, cols - 1)
# initialize the dfs for the first and last row
for j in range(cols):
if grid[0][j] == 'O':
dfs(0, j)
if grid[rows - 1][j] == 'O':
dfs(rows - 1, j)
# change the "O"s that are not marked as "S" to "X"s and the "S"s back to "O"s
for i in range(rows):
for j in range(cols):
if grid[i][j] == 'O':
grid[i][j] = 'X'
elif grid[i][j] == 'S':
grid[i][j] = 'O'
return grid

Keeping Track of Visited Cells

In the above solution, marking each cell as "S" also serves to keep track of the visited cells. We only make recursive calls to the neighboring cells if the current cell is an "O". This way, we avoid visiting the same cell multiple times, as a cell that was previously "O" but is now "S" will not be visited again.
Test Your Knowledge

Login to take the complexity quiz and track your progress

Complexity Analysis

Time Complexity: O(M * N) where M is the number of rows and N is the number of columns in the grid. We perform a DFS traversal (visiting each cell at most once) and then iterate through the entire grid to update the cell values.

Space Complexity: O(M * N) where M is the number of rows and N is the number of columns in the grid. We have to allocate space for each recursive call in the call stack, which can be at most O(M * N).

Mark as read

Next: Pacific Atlantic Water Flow

Your account is free and you can post anonymously if you choose.

Unlock Premium Coding Content

Interactive algorithm visualizations
Guided Practice
Recent interview questions
Learn More
Reading Progress

On This Page

Explanation

Keeping Track of Visited Cells

Questions
Meta SWE Interview QuestionsAmazon SWE Interview QuestionsGoogle SWE Interview QuestionsOpenAI SWE Interview QuestionsEngineering Manager (EM) Interview Questions
Learn
Learn System DesignLearn DSALearn BehavioralLearn ML System DesignLearn Low Level DesignGuided Practice
Links
FAQPricingGift PremiumHello Interview Premium
Legal
Terms and ConditionsPrivacy PolicySecurity
Contact
About UsProduct Support

7511 Greenwood Ave North Unit #4238 Seattle WA 98103


© 2026 Optick Labs Inc. All rights reserved.

Login to track your progress