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


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'
        
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值