Surrounded Regions
Flip every O region that can't reach the edge to X, after first marking the O cells joined to the edge.
The problem
You get a grid board of "X" and "O" cells. A region is a group of "O" cells joined through up, down, left or right steps, and it is surrounded when none of its cells lies on the edge of the board. Change every cell of every surrounded region to "X", in place; the function returns nothing.
Input board = [["X", "X", "X", "X", "X"], ["X", "O", "O", "X", "X"], ["X", "X", "O", "X", "O"], ["X", "O", "X", "X", "O"]]
Output [["X", "X", "X", "X", "X"], ["X", "X", "X", "X", "X"], ["X", "X", "X", "X", "O"], ["X", "O", "X", "X", "O"]]
The three O cells in the middle can't reach the edge, so they flip. The two O cells on the right edge and the one on the bottom edge stay.
Input board = [["X", "X", "X"], ["X", "O", "X"], ["X", "X", "X"]]
Output [["X", "X", "X"], ["X", "X", "X"], ["X", "X", "X"]]
The single O is boxed in on all four sides, so it becomes X.
How to spot the pattern
- Whether a group survives depends on whether it connects to the edge of the grid.
- It is easier to find the groups that reach the edge than to prove that a group is closed in.
The idea
A region survives exactly when it touches the edge, so start from the edge. Run a DFS from every "O" on the border and mark everything it reaches as safe with a temporary letter. Any "O" still unmarked afterwards can't reach the edge, so one final sweep turns those into "X" and turns the safe marks back into "O".
Brute force: For every O cell, search separately for a path to the edge, which repeats the same searches and takes O((m * n)^2) time.
Step by step
- 1Write
markSafe(r, c), which stops if the cell is outside the board or is not"O". - 2Otherwise set the cell to a temporary mark such as
"S"and callmarkSafeon its four neighbors. - 3Call
markSafeon every cell of the first and last rows and of the first and last columns. - 4Sweep the whole board, turning each remaining
"O"into"X"and each"S"back into"O".
See the pattern move
The graph bfs and dfs pattern on a small example. Step through it, or press play.
Code
class Solution:
def solve(self, board: List[List[str]]) -> None:
rows, cols = len(board), len(board[0])
def mark_safe(r: int, c: int) -> None:
if r < 0 or r >= rows or c < 0 or c >= cols or board[r][c] != "O":
return
board[r][c] = "S" # joined to the edge, so it stays
mark_safe(r + 1, c)
mark_safe(r - 1, c)
mark_safe(r, c + 1)
mark_safe(r, c - 1)
for r in range(rows):
mark_safe(r, 0)
mark_safe(r, cols - 1)
for c in range(cols):
mark_safe(0, c)
mark_safe(rows - 1, c)
for r in range(rows):
for c in range(cols):
if board[r][c] == "O":
board[r][c] = "X" # never reached from the edge: captured
elif board[r][c] == "S":
board[r][c] = "O"Complexity
Time
O(m * n)
Space
O(m * n)
Each cell is marked at most once and swept once; the recursion can go m * n calls deep when one region snakes through the whole board.
Watch out for
- Flipping O cells as soon as you see them, before you know whether their region reaches the edge.
- Forgetting to turn the temporary marks back into O at the end.
- Starting the edge search from only some border cells; every cell on all four edges has to be checked.
Follow-up questions
Can you solve it with union-find?
Yes. Join every O cell with its O neighbors, and join each O cell on the edge with one extra dummy node. At the end, flip every O cell that is not in the dummy node's group.
How do you avoid deep recursion on a 200 by 200 board?
Use BFS with a queue that starts from all border O cells at once; the marking logic stays the same.
In Hinglish
Andar se check karne ke bajaye kinaron se shuru karo: border waale har O se DFS chala ke unhe safe mark karo. Jo O safe nahi hue, woh ghire hue hain, unhe X kar do.