Problem 130

Abstract / Summary

Mark all regions surrounded by x that are not connected to an edge as x

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0130.py

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        width  = len(board[0])
        height = len(board)

        @cache
        def markborder(x, y):
            if x < 0 or x > width - 1:
                return
            if y < 0 or y > height - 1:
                return
            if board[y][x] != "O":
                return

            board[y][x] = "!"
            markborder(x-1, y)
            markborder(x+1, y)
            markborder(x, y-1)
            markborder(x, y+1)

        for y in range(height):
            markborder(0, y)
            markborder(width - 1, y)
        for x in range(width):
            markborder(x, 0)
            markborder(x, height - 1)

        for y in range(height):
            for x in range(width):
                if board[y][x] == "O":
                    board[y][x] = "X"
                if board[y][x] == "!":
                    board[y][x] = "O"
33 lines | 964 bytes | submitted September 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 46% (2+ million submissions).

Typical patterns to solve this problem:
  • Array
  • Breadth First Search
  • Depth First Search
  • Matrix
  • Union Find
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the classic “surrounded regions” problem on a two-dimensional board of characters. The algorithm identifies all 'O' cells that are connected to the border and protects them from being flipped, while converting every other 'O' into 'X'. The solution is expressed as a method of a Solution class and operates in-place on the input board.

Key Steps

Determining Board Dimensions

The first two statements compute the horizontal and vertical extents of the board.

width  = len(board[0])
height = len(board)

These values are used throughout the algorithm to bound recursive calls.

Recursive Border Marking

A nested function markborder is defined with memoization via @cache. The function receives coordinates (x, y) and performs several guard checks: it returns immediately if the coordinates lie outside the board limits or if the current cell does not contain 'O'. When a border-connected 'O' is found, it is temporarily changed to '!' and the function recurses in the four orthogonal directions.

@cache
def markborder(x, y):
    if x < 0 or x > width - 1:
        return
    if y < 0 or y > height - 1:
        return
    if board[y][x] != "O":
        return

    board[y][x] = "!"
    markborder(x-1, y)
    markborder(x+1, y)
    markborder(x, y-1)
    markborder(x, y+1)

The use of @cache ensures that each coordinate pair is processed at most once, preventing redundant traversals of already visited cells.

Initiating Traversal from the Border

Two loops iterate over the outermost rows and columns, invoking markborder for every cell on the perimeter. This guarantees that any 'O' reachable from the border, directly or through a chain of adjacent 'O' cells, will be marked.

for y in range(height):
    markborder(0, y)
    markborder(width - 1, y)
for x in range(width):
    markborder(x, 0)
    markborder(x, height - 1)

Final Conversion Pass

A nested loop scans the entire board. Cells still holding 'O' are interior regions and are flipped to 'X'. Cells marked with '!' are restored to 'O', preserving the border-connected regions.

for y in range(height):
    for x in range(width):
        if board[y][x] == "O":
            board[y][x] = "X"
        if board[y][x] == "!":
            board[y][x] = "O"

Edge Cases Handled

The algorithm gracefully handles boards with a single row or a single column because the border loops cover all cells, and the guard checks in markborder prevent out-of-range accesses. Empty boards are not a concern because the method assumes a non-empty rectangular grid, matching the problem constraints. Boards that consist entirely of 'X' result in no changes, as the guard if board[y][x] != "O" stops any recursion. Conversely, a board filled with 'O' will have every cell marked as '!' during the border traversal, and the final pass will restore all cells to 'O', leaving the board unchanged as required.

Performance Optimizations

Memoization via @cache eliminates duplicate work when the recursive search revisits the same coordinate from different paths. This reduces the number of recursive calls dramatically on large contiguous regions of 'O'. The in-place modification of the board avoids auxiliary data structures, keeping memory usage low. By marking visited border cells with a distinct temporary character '!', the algorithm distinguishes between processed and unprocessed cells without extra bookkeeping. The two-phase approach-first marking, then converting-ensures that each cell is examined a constant number of times, leading to efficient execution even on maximal board sizes.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big square grid that looks like a checkerboard, filled with letters. Some spots have an O, some have an X, and some are empty. This code is like a little explorer moving around the board to find special spots.

First, the code measures how wide and tall the grid is so it knows exactly where it can walk. Then it starts a special search at every single spot on the very outside edge of the square. If the explorer finds an O on the edge, it gives that O a secret name, which is an exclamation mark, so that it knows this O is safe and connects to the outside world. After it labels one, it checks all its neighbors to see if they are O letters too, and it keeps jumping from neighbor to neighbor to hide them all safely until it can't find any more connected to the edge.

After all the safe O letters are marked with exclamation marks, it goes through the grid one last time to clean everything up. It looks at every spot on the entire board to see what is there. If it finds a regular O that was never marked by the explorer, that means it is trapped inside, so the code changes it into an X. If it finds one of the special exclamation marks, it knows that one was safe on the edge, so it turns it back into a regular O. In the end, all the trapped O letters have been turned into X letters, and the lucky ones on the edge get to stay as they were.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.48 | σ = 1.71

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JS
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
bujosa Python
charles-wangkai Java
chenyanzhe C++
everthis JavaScript
FelixFan1122 C#
fengvyi C++
fpdjsns C++
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
linouk23 C++
lkwq007 Python
luangong C++
MacJim C++
qiyuangong Python
ruoru Rust
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vthwang Java
wisdompeak C++
XiaotaoGuo C++
zfang399 C++
53 links | 37 authors | 9 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Surrounded Regions - Graph - Leetcode 130 - Python'
NeetCode 15 mins
Surrounded Regions - Graph - Leetcode 130 - Python
YouTube video 'Surrounded Regions | Leetcode #130'
Techdose 14 mins
Surrounded Regions | Leetcode #130
YouTube video 'LeetCode 130. Surrounded Regions (Algorithm Explained)'
Nick White 7 mins
LeetCode 130. Surrounded Regions (Algorithm Explained)
YouTube video 'Surrounded Regions | LeetCode 130 | C++, Java, Python'
Knowledge Center 22 mins
Surrounded Regions | LeetCode 130 | C++, Java, Python
YouTube video '[Java] Leetcode 130. Surrounded Regions [Search #3]'
Eric Programming 14 mins
[Java] Leetcode 130. Surrounded Regions [Search #3]
YouTube video 'LeetCode 130. Surrounded Regions 中文解释 Chinese Version'
happygirlzt 9 mins
LeetCode 130. Surrounded Regions 中文解释 Chinese Version
YouTube video 'Surrounded Regions | Leetcode 130 | Live coding session 🔥🔥🔥| DFS with a trick'
Coding Decoded 10 mins
Surrounded Regions | Leetcode 130 | Live coding session 🔥🔥🔥| DFS with a trick
YouTube video 'surrounded regions | surrounded regions leetcode | leetcode 130 | graph matrix dfs'
Naresh Gupta 10 mins
surrounded regions | surrounded regions leetcode | leetcode 130 | graph matrix dfs
YouTube video 'Surrounded Regions | Day 17 | [June LeetCoding Challenge] [Leetcode #130] [2020]'
Algorithms Made Easy 4 mins
Surrounded Regions | Day 17 | [June LeetCoding Challenge] [Leetcode #130] [2020]
YouTube video 'LeetCode #130: Surrounded Regions (DFS) Code Explained'
Random Coder 15 mins
LeetCode #130: Surrounded Regions (DFS) Code Explained
YouTube video 'LeetCode 130 | Surrounded Regions | Union Find | Java'
Sleepy Cracker 11 mins
LeetCode 130 | Surrounded Regions | Union Find | Java
YouTube video 'LeetCode 130. Surrounded Regions | Medium | Algorithm Explained | C++'
Cherry Coding [IIT-G] 8 mins
LeetCode 130. Surrounded Regions | Medium | Algorithm Explained | C++
YouTube video 'Daily Leetcode #580: Nov 01, 2021 - 130. Surrounded Regions'
Programming Live with Larry 12 mins
Daily Leetcode #580: Nov 01, 2021 - 130. Surrounded Regions
YouTube video 'Daily Leetcode #78: Jun 17, 2020 - 130. Surrounded Regions'
Programming Live with Larry 17 mins
Daily Leetcode #78: Jun 17, 2020 - 130. Surrounded Regions
YouTube video '130. Surrounded Regions | Leetcode Medium | Cpp | Java | Python | Javascript'
Komal Pal 18 mins
130. Surrounded Regions | Leetcode Medium | Cpp | Java | Python | Javascript
YouTube video '84. Leetcode 130. Surrounded Regions : Javascript'
Web Fusion with Bharadwaj 27 mins
84. Leetcode 130. Surrounded Regions : Javascript
YouTube video 'Surrounded Regions - LeetCode #130 - C++'
Sean Chuah 7 mins
Surrounded Regions - LeetCode #130 - C++
YouTube video 'Surrounded Regions |LeetCode 130 | Coders Camp'
Coders Camp 11 mins
Surrounded Regions |LeetCode 130 | Coders Camp
YouTube video 'Leetcode 130: Surrounded Regions in Telugu | DFS Recursive | Python DSA | srkcodes'
Srk Codes 12 mins
Leetcode 130: Surrounded Regions in Telugu | DFS Recursive | Python DSA | srkcodes
YouTube video 'LeetCode 130: Surrounded Regions | C# Solution | DFS/BFS Approach'
Code Scribbler 5 mins
LeetCode 130: Surrounded Regions | C# Solution | DFS/BFS Approach
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

1 medium
2 solutions   September 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality