zoukankan      html  css  js  c++  java
  • leetcode130 Surrounded Regions

     1 """
     2 Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
     3 A region is captured by flipping all 'O's into 'X's in that surrounded region.
     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 Explanation:
    15 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.
    16 """
    17 """
    18 先将边界为'O'的存入队列中,然后遍历队列,两种情况
    19 1.边界'O'相连的'O'
    20 2.边界上为'O'(已经在队列中了)
    21 将这些'O'变为'*'
    22 最后再重新遍历,将所有'O'变为'X',所有'*'变为'O'
    23 """
    24 class Solution:
    25     def solve(self, board):
    26         """
    27         Do not return anything, modify board in-place instead.
    28         """
    29         if not board:
    30             return []
    31         m = len(board)
    32         n = len(board[0])
    33         queue = []
    34         for i in range(m):
    35             for j in range(n):
    36                 if board[i][j] == 'O':
    37                     if i == 0 or i == m - 1 or j == 0 or j == n - 1:
    38                         queue.append((i, j))
    39         while queue:
    40             i, j = queue.pop(0)
    41             if 0 <= i < m and 0 <= j < n and board[i][j] == 'O':
    42                 board[i][j] = '*'
    43                 for x, y in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]:
    44                     queue.append((x, y))
    45 
    46         for i in range(m):
    47             for j in range(n):
    48                 if board[i][j] == 'O':
    49                     board[i][j] = 'X'
    50                 if board[i][j] == '*':
    51                     board[i][j] = 'O'
  • 相关阅读:
    线性变换 矩阵
    【安全】安全测试基本切入点
    【产品】汉语言基础对产品经理的重要性
    【Selenium】自动化调试后C盘越来越大
    【记录】让人淡疼的BUG之参数传送错误
    【转载】Java 升级到jdk7后DbVisualizer 6 启动空指针的处理方案
    cocoapods 报错
    mac 版 Pycharm 激活
    Foxmail添加gmail密码错误
    Apple 相关官方地址
  • 原文地址:https://www.cnblogs.com/yawenw/p/12459114.html
Copyright © 2011-2022 走看看