这道题思路比较直接 就是 BFS,但是直接bfs会超时,那么考虑到有n个 blocked的点,那么最大围成的区域的点数应该不大于1+2+3+…+n-1 = n(n-1)/2,因此我们从两个方向source和target出发看是否会被blocked掉,如果访问的点的个数已经超过n(n-1)/2,那么肯定有一条通路。
class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
blocked = {tuple(b):1 for b in blocked}
def bfs(source, target):
q, vt, count = [source], {tuple(source):1}, 1
while len(q) > 0:
v = q.pop(0)
x, y = v[0], v[1]
for dx, dy in [[0,-1],[1,0],[0,1],[-1,0]]:
tmpx, tmpy = x + dx, y + dy
if [tmpx, tmpy] == target:
return True
if (tmpx, tmpy) not in blocked and (tmpx, tmpy) not in vt and 0<=tmpx<10**6 and 0<=tmpy<10**6:
q.append([tmpx, tmpy])
count += 1
vt[(tmpx, tmpy)] = 1
if count > 19900:
return True
return False
return bfs(source, target) and bfs(target, source)