Phase 1: The inside-out approach — discover why it fails

The Obvious Approach

Here is a grid of X's and O's. The task: find every O that is completely surrounded by X's and flip it to X. The immediately obvious move is to check each O individually: do a flood fill, see if the region reaches the border. If it doesn't touch any border, it's surrounded. Flip it.

I wrote this first. It passed small test cases. Then I looked at the constraints: up to 200×200. For each O-region I'd launch a full DFS. If the grid has m*n O's, each DFS is O(m*n). Total: O((m*n)²). My brain briefly flashed back to the Time Limit Exceeded errors I'd seen on Pacific Atlantic. Same problem, different costume.

But the real issue is subtler than raw time complexity. The inside-out approach asks the WRONG question. For each region, you need to prove it IS surrounded — which requires checking whether ANY cell in the entire region touches the border. You're searching for the absence of an escape route. And proving absence is harder than proving presence.

The warden metaphor: imagine checking every prisoner cell to see “are you still here?” You walk to each cell, look inside, check if they escaped through any gap in the wall. Meanwhile, the exits are right there. Why not just guard the exits and see who tries to walk out?

FIG. 1 — TAP AN INTERIOR O TO SIMULATE THE INSIDE-OUT FLOOD FILL CHECK

Tap an interior O cell to trace the flood fill