边工作边刷题:70天一遍leetcode: day 13-2

Surrounded Regions

要点

  • 之所以从边上开始dfs/bfs,是因为中间的点是没法直接判断是否被包围的,而从边上走,可以立刻判断点是连通的。
  • 这题不需要visited,直接用board上的mark来判断,因为如果是’X’,本来就不继续了,而如果是’O’。只有被mark了,才确定是通的,也就是visited,而没mark的话,从其他路径还要继续判断。

dfs对大size会有Runtime Error:stack overflow了,因为dfs最坏深度可能是整个矩阵的size。所以只能用bfs

class Solution(object):
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        def fill(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]='D'
        def bfs(x, y):
            if board[x][y]=='O':queue.append((x,y)); fill(x,y)
            while queue:
                curr=queue.pop(0); i=curr[0]; j=curr[1]
                fill(i+1,j);fill(i-1,j);fill(i,j+1);fill(i,j-1)
        if len(board)==0: return
        m=len(board); n=len(board[0]); queue=[]
        for i in range(n):
            bfs(0,i); bfs(m-1,i)
        for j in range(1, m-1):
            bfs(j,0); bfs(j,n-1)
        for i in range(m):
            for j in range(n):
                if board[i][j] == 'D': board[i][j] = 'O'
                elif board[i][j] == 'O': board[i][j] = 'X'
原文地址:https://www.cnblogs.com/absolute/p/5675837.html