← Uber bank

Uber · Question 44 · Graphs

Surrounded Regions

GraphsPythoncode⏱ O(m×n)💾 O(m×n)
Product-based

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

  1. 1DFS from every border 'O', marking escapes as '#'.
  2. 2Flip remaining 'O's to 'X'.
  3. 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.
yesnoyesno↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyes↻ repeat↻ repeat↻ repeatyesnoyes↻ repeat↻ repeatyesnoSTARTboardif not board or notboard[0]RETURNrows, cols = len(board),len(board[0])DEFINE dfs(r, c)if r < 0 or r >= rowsor c < 0 or c >= colsor board[r][c] != 'O'RETURNboard[r][c] = '#'for dr, dc in [(1, 0),(-1, 0), (0, 1), (0,-1)]dfs(r + dr, c + dc)for r in range(rows)for c in [0, cols - 1]if board[r][c] == 'O'dfs(r, c)for c in range(cols)for r in [0, rows - 1]if board[r][c] == 'O'dfs(r, c)for r in range(rows)for c in range(cols)if board[r][c] == 'O'board[r][c] = 'X'elif board[r][c] =='#'board[r][c] = 'O'DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))board = [[c for c innext(it)] for _ inrange(m)]solve(board)print(board)if __name__ =="__main__"main()END
  • 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