130被围绕的区域
题目:给定一个二维的矩阵,包含 'X'
和 'O'
(字母 O)。找到所有被 'X'
围绕的区域,并将这些区域里所有的 'O'
用 'X'
填充。
来源:https://leetcode-cn.com/problems/surrounded-regions/
法一:自己的代码
思路:先绕外围走一圈,将所有与外围相连的岛屿都标记为True,然后把bool数组中位置为False的置为‘X’,为了节省空间可以直接将外围的‘O’,改为‘A’,然后再替换。
from typing import List class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ r_length = len(board) if r_length <= 2: return c_length = len(board[0]) if c_length <= 2: return directions = [[0,1],[0,-1],[1,0],[-1,0]] marked = [[False] * c_length for i in range(r_length)] # 定义用于标记的函数 def judge(r,c): # 如果没有被遍历过,且为'O'则进行遍历 if not marked[r][c] and board[r][c] == 'O': # 先将该位置置为True marked[r][c] = True # 将与该位置相连的所有'O’都置为True,表示已经遍历过, queue = [] queue.append((r,c)) while queue: r,c = queue.pop(0) for p,q in directions: # 注意这里的新位置要用新的变量存储,不可用原先的r,c r_new = r + p c_new = c + q if 0 <= r_new < r_length and 0 <= c_new < c_length and board[r_new][c_new] == 'O' and not marked[r_new][c_new]: # 放入队列,等待遍历 queue.append((r_new,c_new)) # 遍历过的位置,且为'O'的都置为True, marked[r_new][c_new] = True # 先遍历最外围一圈,把与最外层相连的岛屿标记为True for r in range(r_length): if r in [0,r_length-1]: for c in range(c_length): judge(r, c) else: for c in [0,c_length-1]: judge(r, c) print(marked) # 最后将中间的'O'变为’X' for r in range(1, r_length): for c in range(1, c_length): if not marked[r][c]: board[r][c] = 'X' print(board) if __name__ == '__main__': solution = Solution() # result = solution.solve([["X","X","X","X"], # ["X","O","O","X"], # ["X","X","O","X"], # ["X","O","X","X"]]) result = solution.solve([["X","X","X","X"], ["X","O","O","X"], ["X","X","O","X"], ["X","O","X","X"]]
ttt