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的代码

你可能感兴趣的:(leetcode)