Leetcode 130. Surrounded Regions
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.
For 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
keys: 1. BFS from the most outer layer.
1 class Solution(object): 2 def solve(self, board): 3 """ 4 :type board: List[List[str]] 5 :rtype: void Do not return anything, modify board in-place instead. 6 """ 7 8 if not board: 9 return 10 11 m = len(board) 12 n = len(board[0]) 13 14 queue = [] 15 16 for i in range(m): 17 for j in range(n): 18 if i == 0 or j == 0 or i == m -1 or j == n-1: 19 if board[i][j] == 'O': 20 queue.append([i,j]) 21 22 while queue: 23 [p,q] = queue.pop(0) 24 board[p][q] ='V' 25 if self.isValid(p+1, q, m, n) and board[p+1][q] == 'O': 26 queue.append([p+1, q]) 27 if self.isValid(p-1, q, m, n) and board[p-1][q] == 'O': 28 queue.append([p-1, q]) 29 if self.isValid(p, q+1, m, n) and board[p][q+1] == 'O': 30 queue.append([p, q+1]) 31 if self.isValid(p, q-1, m, n) and board[p][q-1] == 'O': 32 queue.append([p, q-1]) 33 34 for i in range(m): 35 for j in range(n): 36 if board[i][j] == 'V': 37 board[i][j] ='O' 38 elif board[i][j] == 'O': 39 board[i][j] ='X' 40 41 def isValid(self, i,j, m, n): 42 return i>0 and i<m and j>0 and j<n 43 44

浙公网安备 33010602011771号