Problem
Given an m x n matrix board containing ‘X’ and ‘O’, capture all regions that are 4-directionally surrounded by ‘X’.
A region is captured by flipping all 'O’s into 'X’s in that surrounded region.
Algorithm
Recursion. Set all the “O” to “#” and change them back if some point can be visit from the edges.
Code
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board:
return []
row = len(board)
col = len(board[0])
def dfs(r, c, i, j):
if i < 0 or i >= r or j < 0 or j >= c:
return
if board[i][j] == "O":
board[i][j] = "#"
dfs(r, c, i-1, j)
dfs(r, c, i+1, j)
dfs(r, c, i, j-1)
dfs(r, c, i, j+1)
for r in range(row):
dfs(row, col, r, 0)
dfs(row, col, r, col-1)
for c in range(col):
dfs(row, col, 0, c)
dfs(row, col, row-1, c)
for r in range(row):
for c in range(col):
if board[r][c] == "O":
board[r][c] = "X"
if board[r][c] == "#":
board[r][c] = "O"