LeetCode 130: Surrounded Regions — Python Solution

LeetCode 130: Surrounded Regions is a Medium graph general problem. This Python walkthrough develops a boundary flood fill solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicGraph General
Reusable patternboundary flood fill
ComplexityO(mn) time and O(mn) worst-case space

Recognizing the pattern

Graph traversal separates reachability from representation: adjacency describes possible moves, while a visited structure prevents repeated work.

For this problem specifically, mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks. The invariant worth writing beside the code is: Marked cells are exactly the open cells connected to some boundary open cell.

Step-by-step algorithm

  1. Identify the input state consumed by solve(board) and initialize the data required by the boundary flood fill pattern.
  2. Mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks.
  3. After each update, verify the page’s central invariant: Marked cells are exactly the open cells connected to some boundary open cell.
  4. Finish only after the boundary behavior is covered: Boundary cells can never be captured; thin boards are handled naturally.

Python solution

class Solution:
    def solve(self, board):
        if not board: return
        rows, cols = len(board), len(board[0])
        def mark(r, c):
            if r < 0 or c < 0 or r == rows or c == cols or board[r][c] != "O": return
            board[r][c] = "S"
            mark(r + 1, c); mark(r - 1, c); mark(r, c + 1); mark(r, c - 1)
        for r in range(rows): mark(r, 0); mark(r, cols - 1)
        for c in range(cols): mark(0, c); mark(rows - 1, c)
        for r in range(rows):
            for c in range(cols):
                board[r][c] = "O" if board[r][c] == "S" else "X"

Reading the implementation

The main entry point is solve(board). The named working state includes rows; those variables make the boundary flood fill state visible instead of hiding it in incidental control flow.

The implementation uses 4 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks.

Correctness argument

Initialization. The data structure starts with exactly the information known before any input element is processed.

Preservation. Mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks. Each update records the current item without invalidating earlier decisions; consequently, marked cells are exactly the open cells connected to some boundary open cell.

Termination. The traversal consumes a finite input or finite state space. At the end, the invariant covers the complete input, which is precisely the condition required for the returned result.

Complexity and trade-offs

O(mn) time and O(mn) worst-case space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

DFS and BFS often have the same asymptotic cost; choose DFS for recursive structure and BFS when distance or processing order matters. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

board=[list("XXXX"),list("XOOX"),list("XXOX"),list("XOXX")]; Solution().solve(board); assert board==[list("XXXX"),list("XXXX"),list("XXXX"),list("XOXX")]

Common mistakes and edge cases

  • Problem-specific boundary: Boundary cells can never be captured; thin boards are handled naturally.
  • Pattern-level pitfall: Mark a state when it is discovered rather than after all of its neighbors are processed, or cycles can enqueue it repeatedly.
  • Invariant check: after every update, confirm that marked cells are exactly the open cells connected to some boundary open cell.

Interview review checklist

  • Explain why boundary flood fill matches the structure of this input.
  • State the invariant in one sentence before tracing code: Marked cells are exactly the open cells connected to some boundary open cell.
  • Derive O(mn) time and O(mn) worst-case space from how many times each element or state is visited.
  • Test the boundary explicitly: Boundary cells can never be captured; thin boards are handled naturally.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 200. Number of Islands · Next: 133. Clone Graph