CodeArchon

mediumGraphsAmazon

Captured Region Flipper

A board-game solver flips captured enemy territories to friendly, keeping only groups touching the board edge safe.

Given an m×n matrix of 'X' and 'O', flip every 'O' NOT connected to a border 'O' into 'X'.

Choose approach

X
X
X
X
X
O
O
X
X
X
O
X
X
S
X
X
1/2
Narrationstep 1 of 2

Mark border-connected O's as safe (S).

1def solve(b):
2 R, C = len(b), len(b[0])
3 def dfs(r, c):
4 if r<0 or r>=R or c<0 or c>=C or b[r][c] != 'O': return
5 b[r][c] = 'S'
6 dfs(r+1,c); dfs(r-1,c); dfs(r,c+1); dfs(r,c-1)
7 for r in range(R): dfs(r, 0); dfs(r, C-1)
8 for c in range(C): dfs(0, c); dfs(R-1, c)
9 for r in range(R):
10 for c in range(C):
11 b[r][c] = 'O' if b[r][c] == 'S' else 'X'
Variables
stage=mark-safe

How to think about it

  1. Only border-reachable 'O's survive.
  2. Mark survivors with a temp sentinel to distinguish from doomed 'O's.
  3. Final linear pass does the flip.

Edge cases to catch in interview

  • Empty grid -> no-op.
  • No 'O' touches border -> every O flipped.

Examples

Example 1unchanged border Os
{"grid":[["X","O"],["O","X"]]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed