• 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'
  • 相关阅读:
    java HTTP代码示例
    eclipse创建文件package,source folder和folder区别及相互转换
    spring 及 spring boot 资源文件配置
    深入理解Java枚举类型(enum)
    Linux环境变量配置的三个方法--/etc/profile,~/.bashrc,shell
    JAXB和XStream比较
    java将配置信息写在数据库(利用反射)
    【大数据实战】Logstash采集->Kafka->ElasticSearch检索
    Linux 安装rabbitmq 遇到的一些问题
    Linux 下的jdk安装
  • 原文地址:https://www.cnblogs.com/yawenw/p/12459114.html
Copyright © 2020-2023  润新知