LeetCode 被圍繞的區域

給定一個二維的矩陣,包含 'X' 和 'O'(字母 O)。函數

找到全部被 'X' 圍繞的區域,並將這些區域裏全部的 'O' 用 'X' 填充。spa

示例:code

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

運行你的函數後,矩陣變爲:blog

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

解釋:io

被圍繞的區間不會存在於邊界上,換句話說,任何邊界上的 'O' 都不會被填充爲 'X'。 任何不在邊界上,或不與邊界上的 'O' 相連的 'O' 最終都會被填充爲 'X'。若是兩個元素在水平或垂直方向相鄰,則稱它們是「相連」的。class

 

使用bfs,由於不能對邊界上的連通區域填充,因此,須要提早將邊界上的連通區域作特殊標記,一樣調用bfs將其填充爲「M」。最後在改回「O」便可。object

最後,對中間的連通區域調用bfs進行填充。List

 

 1 class Solution(object):
 2     def bfs(self, r, c, square, t):
 3         # t == 1邊緣填充, t == 0中央填充
 4         nearr = [-1,0,1,0]
 5         nearc = [0,1,0,-1]
 6         if square[r][c] != "O": return
 7         if t == 1:
 8             square[r][c] = "M"
 9         elif t == 0:
10             square[r][c] = "X"
11         for i in range(4):
12             if r+nearr[i] >= 0 and  r+nearr[i] < len(square) and c+nearc[i] >= 0 and c+nearc[i]<len(square[0]):
13                 self.bfs(r+nearr[i], c+nearc[i], square, t)
14     def solve(self, board):
15         """
16         :type board: List[List[str]]
17         :rtype: void Do not return anything, modify board in-place instead.
18         """
19         if board == []: return
20         elif board[0] == []: return
21         
22         # 首先,將邊緣的O進行標記,標記爲M
23         for i in range(len(board[0])):
24             if board[0][i] == "O":
25                 self.bfs(0, i, board, 1)
26         for i in range(len(board[0])):
27             if board[len(board)-1][i] == "O":
28                 self.bfs(len(board)-1, i, board, 1)
29         for i in range(len(board)):
30             if board[i][0] == "O":
31                 self.bfs(i, 0, board, 1)
32         for i in range(len(board)):
33             if board[i][len(board[0])-1] == "O":
34                 self.bfs(i, len(board[0])-1, board, 1)
35 
36         # 檢查中間的連通區域
37         for i in range(0, len(board)):
38             for j in range(0, len(board[0])):
39                 if board[i][j] == "O":
40                     self.bfs(i, j, board, 0)
41 
42         for i in range(len(board)):
43             for j in range(len(board[0])):
44                 if board[i][j] == "M":
45                     board[i][j] = "O"
相關文章
相關標籤/搜索