130. Surrounded Regions python

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’,替换成'X'

思路:遍历外围一圈,如果是O替换成D,然后判断相邻的四个方位是否有O,也换成D。最后整个数组中是O的就是需要替换成X的数据

方法:判断四个相邻的方位是否有O,需要用到DFS与BFS,DFS方法是如果上方有O,继续往上方判断,直到没有O,然后往右判断一位,然后又是往上判断是否有O...需要用到递归的方法,耗费资源。BFS方法是先判断四个方向是否有O,有的话顺序进队,然后从队中取出第一个,继续判断四周,再进队....此方法只需要队列,不需要递归

下面是BFS代码

class Solution(object):
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: None Do not return anything, modify board in-place instead.
        """
        if(len(board)==0):
            return 
        m=len(board)
        n=len(board[0])
        q=[]
        def fill(x,y):
            if x<0 or x>m-1 or y<0 or y>n-1 or not board[x][y]=='O':
                return 
            board[x][y]='D'
            q.append((x,y))
        def bfs(x,y):
            if board[x][y]=='O':
                fill(x,y)
            while(q):
                cur=q.pop(0)
                i=cur[0]
                j=cur[1]
                fill(i-1,j)
                fill(i+1,j)
                fill(i,j-1)
                fill(i,j+1)
                
        for i  in range(m):
            bfs(i,0)
            bfs(i,n-1)
        for j in range(n):
            bfs(0,j)
            bfs(m-1,j)
        
        
        for i in range(m):
            for j in range(n):
                if(board[i][j]=='O'):
                    board[i][j]='X'
                if(board[i][j]=='D'):
                    board[i][j]='O'
                       
   
        

参考https://www.cnblogs.com/zuoyuan/p/3765434.html。该博主给出了DFS与BFS的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值