北美程序员面试干货

LeetCode 130 [Surrounded Regions

2016-07-21  本文已影响276人  Jason_Yuan

原题

给一个二维的矩阵,包含 'X' 和 'O', 找到所有被 'X' 围绕的区域,并用 'X' 填充满。

样例
给出二维矩阵:

X X X X
X O O X
X X O X
X O X X

把被 'X' 围绕的区域填充之后变为:

X X X X
X X X X
X X X X
X O X X

解题思路

完整代码

import Queue
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 > height-1 or y < 0 or y > width-1 or board[x][y] != "O":
                return
            MyQueue.put((x, y))
            board[x][y] = "D"
            
        def bfs(x, y):
            if board[x][y] == "O":
                fill(x, y)
                
            while not MyQueue.empty():
                current = MyQueue.get()
                i, j = current[0], current[1]
                fill(i+1, j)
                fill(i-1, j)
                fill(i, j+1)
                fill(i, j-1)
                
        if len(board) == 0:
            return
        
        height, width, MyQueue = len(board), len(board[0]), Queue.Queue()
        for i in range(width):
            bfs(0, i)
            bfs(height - 1, i)
        
        for j in range(1, height - 1):
            bfs(j, 0)
            bfs(j, width - 1)
            
        for i in range(height):
            for j in range(width):
                if board[i][j] == "D":
                    board[i][j] = "O"
                elif board[i][j] == "O":
                    board[i][j] = "X"
上一篇下一篇

猜你喜欢

热点阅读