leetcode第130题,迷宫题的近似题,深搜广搜问题,但是据说这道题用深搜会溢出,所以还是使用广搜比较好。
分析问题可以看出,所有与边界搭边的O全部都要被保留,因此这道题应该反过来考虑,那就是不要考虑哪些圆圈被包围,而是哪些圆圈在边界上,然后依次为基础进行广搜,搜索出所有与边界圆圈接壤的圆圈,并把它们做一个标记,此时剩下的就是被包围的圆圈了,再做一次遍历,把包围的圆圈改成X,然后标记过的位置再改回圆圈即可。
注意,这道题的python数据类型很坑,虽然输入时双重列表,但是测试数据却是字符串列表,究其原因是因为python字符串是不可变类型,是不能原地修改的。这里OJ内部应该有一个转换程序。
class Solution(object):
def solve(self, board):
"""
:type board: List[List[str]]
:rtype: void Do not return anything, modify board in-place instead.
"""
queue = []
m = len(board)
if m <= 2 or board is None: return
n = len(board[0])
if n <= 2: return
for i in range(n):
if board[0][i] == 'O':
queue.append((0,i))
for i in range(n):
if board[m-1][i] == 'O':
queue.append((m-1,i))
for i in range(m):
if board[i][0] == 'O':
queue.append((i,0))
for i in range(m):
if board[i][n-1] == 'O':
queue.append((i,n-1))
#queue = list(set(queue))
print queue
go = [[0,1],[0,-1],[1,0],[-1,0]]
while len(queue) != 0:
head = queue.pop()
board[head[0]][head[1]] = '*'
for i in range(4):
nextx = head[0]+go[i][0]
nexty = head[1]+go[i][1]
if nextx < m and nextx >= 0 and nexty < n and nexty >= 0:
if board[nextx][nexty] == 'O':
board[nextx][nexty] = '*'
queue.append((nextx,nexty))
for i in range(m):
for j in range(n):
if board[i][j] == 'O':
board[i][j] = 'X'
if board[i][j] == '*':
board[i][j] = 'O'