Given a 2D board containing 'X'
and 'O'
(the letter O), capture all regions surrounded by 'X'
.
A region is captured by flipping all 'O'
s into 'X'
s in that surrounded region.
Example:
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
Explanation:
Surrounded regions shouldn’t be on the border, which means that any 'O'
on the border of the board are not flipped to 'X'
. Any 'O'
that is not on the border and it is not connected to an 'O'
on the border will be flipped to 'X'
. Two cells are connected if they are adjacent cells connected horizontally or vertically.
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: None Do not return anything, modify board in-place instead.
"""
def dfs(i, j):
visited[i][j] = True
if i > 0 and board[i-1][j] == 'O' and not visited[i-1][j]:
dfs(i-1, j)
if i < height-1 and board[i+1][j] == 'O' and not visited[i+1][j]:
dfs(i+1, j)
if j > 0 and board[i][j-1] == 'O' and not visited[i][j-1]:
dfs(i, j-1)
if j < width-1 and board[i][j+1] == 'O' and not visited[i][j+1]:
dfs(i, j+1)
# dfs(i, j+1)
height = len(board)
if height <= 2:
return
width = len(board[0])
if width <= 2:
return
visited = [[False for _ in range(width)] for _ in range(height)]
for i in range(width):
if board[0][i] == 'O' and not visited[0][i]:
dfs(0, i)
if board[-1][i] == 'O' and not visited[-1][i]:
dfs(height-1, i)
for i in range(height):
if board[i][0] == 'O' and not visited[i][0]:
dfs(i, 0)
if board[i][width-1] == 'O' and not visited[i][width-1]:
dfs(i, width-1)
# print(visited)
for h in range(height):
for w in range(width):
if board[h][w] == 'O' and not visited[h][w]:
board[h][w] = 'X'
return