[leetcode] 130. Surrounded Regions

题目

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'.

思路

根据题意,包围区域是不和边界连接的区域,那么可以先找出所有与边界连接的区域,而这些区域以外的区域都是包围区域,将他们转为X即可。

代码

python版本:

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        used = [[0 for _ in range(len(board[0]))] for _ in range(len(board))]

        def dfs(i, j):
            if i < 0 or i >= len(board) or j < 0 or j >= len(board[0]) or board[i][j] == "X" or used[i][j]:
                return
            used[i][j] = 1
            [dfs(i+x, j+y) for x, y in ((0, 1), (0, -1), (1, 0), (-1, 0))]
        [dfs(0, j) for j in range(len(board[0]))]
        [dfs(len(board)-1, j) for j in range(len(board[0]))]
        [dfs(i, 0) for i in range(len(board))]
        [dfs(i, len(board[0])-1) for i in range(len(board))]
        for i in range(1, len(board)-1):
            for j in range(1, len(board[0])-1):
                if used[i][j] == 0:
                    board[i][j] = "X"

posted @ 2022-03-28 13:52  frankming  阅读(17)  评论(0编辑  收藏  举报