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"
Difficulty
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
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 200: Number of Islands
Solved On The Same Day
- problem 200: Number of Islands
Extra
- 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