Advertisement
jinhuang1102

130. Surrounded Regions

Nov 18th, 2018
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
  2. A region is captured by flipping all 'O's into 'X's in that surrounded region.
  3.  
  4. Example:
  5. X X X X
  6. X O O X
  7. X X O X
  8. X O X X
  9. After running your function, the board should be:
  10. X X X X
  11. X X X X
  12. X X X X
  13. X O X X
  14.  
  15. Explanation:
  16. 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.
  17.  
  18. 解法:这道题用到 BFS 做法是先走一圈边界值,如果边界值为"O",那么由边界值的"O"开始往四个方向遍历,每遍历到一个新的"O",就把"O"变成"$"。让后在从matrix的[0][0]位开始重新遍历,遇到"O"就变成"X",遇到"$"就变成"O"
  19.  
  20. class Solution(object):
  21.     def solve(self, board):
  22.         """
  23.        :type board: List[List[str]]
  24.        :rtype: void Do not return anything, modify board in-place instead.
  25.        """
  26.         if board == None or len(board) == 0 or len(board[0]) == 0:
  27.             return
  28.        
  29.         q = collections.deque()
  30.         for i in range(len(board)):
  31.             for j in range(len(board[0])):
  32.                 if i == 0 or j == 0 or i == len(board) - 1 or j == len(board[0]) - 1:
  33.                     if board[i][j] == 'O':
  34.                         q.append((i,j))
  35.                        
  36.         dx = [0, 0, -1, 1]
  37.         dy = [-1, 1, 0, 0]
  38.         while q:
  39.             x, y = q.popleft()
  40.             board[x][y] = "$"
  41.            
  42.             for d in range(4):
  43.                 rx, ry = x + dx[d], y + dy[d]
  44.                 if rx < 0 or ry < 0 or rx > len(board) - 1 or ry > len(board[0]) - 1:
  45.                     continue
  46.                 else:
  47.                     if board[rx][ry] == "O":
  48.                         q.append((rx, ry))
  49.                    
  50.         for i in range(0, len(board)):
  51.             for j in range(0, len(board[0])):
  52.                 if board[i][j] == "O":
  53.                     board[i][j] = "X"
  54.                 elif board[i][j] == "$":
  55.                     board[i][j] = "O"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement