LeetCode 130: Surrounded Regions — Python Solution

Solve LeetCode 130: Surrounded Regions in Python with a boundary flood fill approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

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

What the problem is testing

Mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks.

Algorithm

  1. Mark all O cells reachable from the boundary as safe, flip every remaining O to X, then restore the safe marks.
  2. Maintain this invariant: Marked cells are exactly the open cells connected to some boundary open cell.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

from collections import Counter, defaultdict, deque, OrderedDict
import random

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"

Why this is correct

The proof follows the maintained state: Marked cells are exactly the open cells connected to some boundary open cell. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

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

Edge cases

Boundary cells can never be captured; thin boards are handled naturally.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


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