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

Posted 张乐乐章

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于130. Surrounded Regions(周围区域问题 广度优先)(代码未完成!!)的主要内容,如果未能解决你的问题,请参考以下文章

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions

130. Surrounded Regions