Introduction
Surrounded Regions is one of the most important Matrix DFS and BFS interview problems.
You are given:
board[][]Goal:
Convert all surrounded O's into X's Rule:
Any O connected to the boundary cannot be captured. Example
X X X XX O O X
X X O X
X O X X
Output:
X X X XX X X X
X X X X
X O X X
Key Observation
Do NOT find:
Captured O's Instead find:
Safe O'sSafe O's are:
Boundary O's and Connected O's Algorithm
1. Traverse boundary.2. Find boundary O's.
3. Run DFS/BFS.
4. Mark safe cells.
5. Convert remaining O's to X's.
6. Restore safe cells.
Dry Run
Input:
X X X X
X O O X
X X O XX O X X
Safe Cell:
Bottom Boundary OCaptured Cells:
Middle O Region Answer:
X X X X
X X X X
X X X XX O X X
Approach : DFS
Explanation
- Start from boundary O's.
- Mark them as safe.
- Visit connected O's.
- Convert remaining O's.
- Restore safe cells.