Surrounded Regions - Complete Solution Guide
Surrounded Regions is LeetCode problem 130, a Medium level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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 : The region is surrounded with 'X' cells if you can connect the region with 'X' cells and none of the region cells are on the edge of the board . To capture a surrounded region , replace all 'O' s with 'X' s in-place within the original board. You do not ne
Detailed Explanation
The problem asks us to capture regions of 'O's in a 2D board that are completely surrounded by 'X's. Capturing a region means replacing all 'O's within that region with 'X's. A region of 'O's is considered surrounded if it's fully enclosed by 'X's and none of the 'O's in that region are connected to the edge of the board. The input is a 2D character array (board), and the output is the modified board (in-place).
Solution Approach
The solution utilizes Depth-First Search (DFS) to identify and mark 'O's that are connected to the border. It then iterates through the board, flipping the remaining 'O's to 'X's (the surrounded regions) and reverting the marked 'O's back to 'O's.
Step-by-Step Algorithm
- Step 1: Iterate through the borders of the board (top, bottom, left, right).
- Step 2: For each 'O' found on the border, initiate a DFS traversal.
- Step 3: The DFS function recursively explores adjacent cells. If an adjacent cell is within bounds and is an 'O', it is marked with a temporary character (e.g., 'T'). The DFS continues recursively from this marked cell.
- Step 4: After the border traversal and DFS marking, iterate through the entire board.
- Step 5: If a cell contains 'O', it means it was not connected to any border 'O' and thus is surrounded. Change it to 'X'.
- Step 6: If a cell contains the temporary character (e.g., 'T'), it means it was connected to a border 'O' and is not surrounded. Change it back to 'O'.
Key Insights
- Insight 1: The key is to identify 'O's that are *not* surrounded. These are the 'O's that are either on the border or connected to 'O's on the border.
- Insight 2: A temporary marker is needed to differentiate between 'O's that are connected to the border ('safe' 'O's) and 'O's that are truly surrounded.
- Insight 3: Depth-First Search (DFS) is an efficient way to traverse and mark all 'O's connected to the border 'O's.
Complexity Analysis
Time Complexity: O(m*n)
Space Complexity: O(m*n)
Topics
This problem involves: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix.
Companies
Asked at: Arcesium, Flipkart, Nutanix, TikTok, Urban Company.