Uber · Question 44 · Graphs
Surrounded Regions
Problem
Given an m x n board containing 'X' and 'O', capture all regions surrounded by 'X' by flipping fully-surrounded 'O's into 'X's.
Approach
Use DFS (or BFS) from border 'O's to mark safe regions temporarily (e.g., mark as '#'). Then flip all other 'O's to 'X' and revert '#' back to 'O'.
Time O(m×n)Space O(m×n)
How it works
- 1DFS from every border 'O', marking escapes as '#'.
- 2Flip remaining 'O's to 'X'.
- 3Restore '#' cells to 'O'.
Sample input / output
Input: 4 4 XXXX XOOX XXOX XOXX Output: [['X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X'], ['X', 'O', 'X', 'X']]
Constraints
m == board.length; n == board[i].length; 1 <= m, n <= 200; cells 'X'/'O'.
Solution — read it, then walk it
Time O(m×n)Space O(m×n)Loops 7Branches 7Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/35
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits