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'
  • 相关阅读:
    搜狗输入法——从繁体改成简体
    java官网下载
    eclipse官网下载
    java拷贝指定文件夹下的指定文件类型
    bat脚本——删除当前文件夹的所有指定文件类型
    windows系统下载地址大全&大白菜下载和教程
    struts2——文件下载自定义文件名,包括中文
    struts2——文件下载(简单的功能)
    nginx官网下载&百度云分享
    Apache HTTP Server——官网下载
  • 原文地址:https://www.cnblogs.com/yawenw/p/12459114.html
Copyright © 2011-2022 走看看