【leetcode】(python) 130. Surrounded Regions周边地区

周边地区

  • Description
  • Example:
  • 题意
  • 解题思路
    • code

130. Surrounded Regions Medium

Description

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.

题意

给定包含“X”和“O”(字母O)的2D板,捕获由“X”包围的所有区域,将所有被包围的”O“翻转成”X“。

解题思路

刚开始做这题就直接将2D板中间循环遍历将”O“改成”X“了,后面发现怎么也不对。因为按我的思路只考虑到了最普通的情况:“O”的四周被“X”包围,其实还有一种反向包围:就是"x"只一个,却也包围了所有”O“。比如说画一个圆,四周包围了圆内,其实也可看作圆内包围了四周。
然后参考了别的解法,将没有包围的”O“翻转成”A“,被包围的还是原”O“,然后重新遍历,将”O“翻转为”X“,"A"翻转为”O“。

code

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        def change(x,y):
            if x<0 or x>m-1 or y<0 or y>n-1 or board[x][y]!='O':
                return 
            queue.append((x,y))
            board[x][y] = 'A'
        
        def dfs(x,y):
            if board[x][y] == 'O':
                change(x,y)
            while queue:
                cur = queue.pop(0)
                i = cur[0]
                j = cur[1]
                change(i+1,j)
                change(i-1,j)
                change(i,j+1)
                change(i,j-1)
        
        if board == []:
            return 
        m = len(board)
        n = len(board[0])
        queue = []
        
        for i in range(n):
            dfs(0,i)
            dfs(m-1,i)
        for j in range(1,m-1):
            dfs(j,0)
            dfs(j,n-1)
        
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'A':
                    board[i][j] = 'O'
                elif board[i][j] == 'O':
                    board[i][j] = 'X'
        

你可能感兴趣的:(LeetCode)