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'
  • 相关阅读:
    虽然非常简单但是效果不错
    Google地图开发总结
    笔记(一):ES6所改良的javascript“缺陷”
    ex6的选择器
    android中的style部分属性值介绍
    Android ImageSwitcher
    c# Winform退出程序的方法
    Android ImageView获取网络图片
    循环向数据库(sql server)插入10W条数据
    Android Handler+Thread实现更新Ui
  • 原文地址:https://www.cnblogs.com/yawenw/p/12459114.html
Copyright © 2011-2022 走看看