動機
複習dfs
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.
Example 1:
Input: board = [[X,X,X,X],[X,O,O,X],[X,X,O,X],[X,O,X,X]]Output: [[X,X,X,X],[X,X,X,X],[X,X,X,X],[X,O,X,X]]Explanation: Surrounded regions should not 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.
Example 2:
Input: board = [[X]]Output: [[X]]
Constraints:
m == board.length
n == board[i].length
1 <= m, n <= 200
board[i][j]
is'X'
or'O'
.
Sol
從邊dfs回去
class Solution:
def solve(self, bs: List[List[str]]) -> None:
def dfs(i,j):
nonlocal bs
if i < 0 or i >= len(bs) or j < 0 or j >= len(bs[0]) or bs[i][j] == "X" or bs[i][j] == "":
return
elif bs[i][j] == "O":
bs[i][j] = ""
[dfs(x,y) for (x,y) in [(i+1,j), (i,j+1), (i-1,j), (i,j-1)]]
[[dfs(i,j) for j in range(len(bs[i]))] for i in [0,len(bs)-1]]
[[dfs(i,j) for j in [0,len(bs[i])-1]] for i in range(len(bs))]
#print(bs)
for i in range(len(bs)):
for j in range(len(bs[i])):
if bs[i][j] == "":
bs[i][j] = "O"
else:
bs[i][j] = "X"