leetcode 130
https://leetcode.com/problems/surrounded-regions/
题目要求把四周被X包围的O块去掉. 所以没有被去掉的O块一定是在边上. 我的想法是标记所有于周边相连的O块即可. 具体方法可以依次使用广度优先.
1, 对周围一圈的O依次使用广度优先(深度优先亦可) 标记为1.
2, 遍历矩阵将O改为X
3, 遍历矩阵将1改回O
`class Solution:
def update_info(self, board, i, j, row_num, col_num):
if i < 0 or j < 0 or i >= row_num or j >= col_num:
return
if board[i][j] == "O":
board[i][j] = "1"
# print(i, j)
for m in (i-1, i+1):
self.update_info(board, m, j, row_num, col_num)
for n in (j+1, j-1):
self.update_info(board, i, n, row_num, col_num)
return
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board or not board[0]:
return
row_num = len(board)
col_num = len(board[0])
if row_num == 1 or col_num == 1:
return
for i in range(row_num):
for j in (0, col_num-1):
self.update_info(board, i, j, row_num, col_num)
for i in (0, row_num - 1):
for j in range(col_num):
self.update_info(board, i, j, row_num, col_num)
for i in range(row_num):
for j in range(col_num):
if board[i][j] == "O":
board[i][j] = "X"
for i in range(row_num):
for j in range(col_num):
if board[i][j] == "1":
board[i][j] = "O"`