• 130. Surrounded Regions(周围区域问题 广度优先)(代码未完成!!)


    Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

    A region is captured by flipping all 'O's into 'X's in that surrounded region.

    For example,

    X X X X
    X O O X
    X X O X
    X O X X
    

    After running your function, the board should be:

    X X X X
    X X X X
    X X X X
    X O X X
    

    反向思索最简单:哪些‘O’是应该保留的?
     从上下左右四个边界往里走,凡是能碰到的
    ‘O’ ,都是跟边界接壤的,应该保留。
     思路:
     对于每一个边界上的‘O’作为起点,做若干次广度
    优先搜索,对于碰到的‘O’,标记为其他某字符Y;
     最后遍历一遍整个地图,把所有的Y恢复成‘O’,把
    所有现有的‘O’都改成‘X’

     1 import Queue
     2 class Solution(object):
     3     def solve(self, board):
     4         """
     5         :type board: List[List[str]]
     6         :rtype: void Do not return anything, modify board in-place instead.
     7         """
     8         def fill(x, y):
     9             if x < 0 or x > height-1 or y < 0 or y > width-1 or board[x][y] != "O":
    10                 return
    11             MyQueue.put((x, y))
    12             board[x][y] = "D"
    13             
    14         def bfs(x, y):
    15             if board[x][y] == "O":
    16                 fill(x, y)
    17                 
    18             while not MyQueue.empty():
    19                 current = MyQueue.get()
    20                 i, j = current[0], current[1]
    21                 fill(i+1, j)
    22                 fill(i-1, j)
    23                 fill(i, j+1)
    24                 fill(i, j-1)
    25                 
    26         if len(board) == 0:
    27             return
    28         
    29         height, width, MyQueue = len(board), len(board[0]), Queue.Queue()
    30         for i in range(width):
    31             bfs(0, i)
    32             bfs(height - 1, i)
    33         
    34         for j in range(1, height - 1):
    35             bfs(j, 0)
    36             bfs(j, width - 1)
    37             
    38         for i in range(height):
    39             for j in range(width):
    40                 if board[i][j] == "D":
    41                     board[i][j] = "O"
    42                 elif board[i][j] == "O":
    43                     board[i][j] = "X"

    参考:https://www.jianshu.com/p/3ea288ffdb68

  • 相关阅读:
    设计模式的概念与作用
    动画回调函数未执行
    使用PathfindingProject Pro 4.0.10实现2D自动寻路
    一些概念和路径记录
    android 数据库添加字符串 添加失败 解决方案
    view的focusable属性改变设置是否可获取光标
    view的clickable属性和点击background颜色改变
    java中一对多 关联建表
    Android 自定义View
    Android 之常用布局
  • 原文地址:https://www.cnblogs.com/zle1992/p/8476221.html
Copyright © 2020-2023  润新知