In a 1 million by 1 million grid, the coordinates of each grid square are (x, y)
with 0 <= x, y < 10^6
.
We start at the source
square and want to reach the target
square. Each move, we can walk to a 4-directionally adjacent square in the grid that isn't in the given list of blocked
squares.
Return true
if and only if it is possible to reach the target square through a sequence of moves.
Example 1:
Input: blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]
Output: false
Explanation:
The target square is inaccessible starting from the source square, because we can't walk outside the grid.
Example 2:
Input: blocked = [], source = [0,0], target = [999999,999999]
Output: true
Explanation:
Because there are no blocked cells, it's possible to reach the target square.
Note:
0 <= blocked.length <= 200
blocked[i].length == 2
0 <= blocked[i][j] < 10^6
source.length == target.length == 2
0 <= source[i][j], target[i][j] < 10^6
source != target
思路:肯定不能暴力搜索,一定要利用block.length 有限制 这个重要约束,
1. 要么就从block出发:考虑那些形成环的block,然后判断source,target在不在里面--------->不work,情况很多,计算量也大
2. 从传统BFS出发,现在BFS、DFS的搜索深度:这里就是用这种方法,要把source、target包起来,最多只能包住范围为block.length内的点(这还要利用边界才做得到,如果是在内部,只能包住范围为block.length/2内的点)
class Solution(object):
def isEscapePossible(self, blocked, source, target):
"""
:type blocked: List[List[int]]
:type source: List[int]
:type target: List[int]
:rtype: bool
"""
dirs=[[1,0],[-1,0],[0,1],[0,-1]]
lim=1000000
block=set()
for s in blocked: block.add(tuple(s))
def can_escape(start):
q=[start]
vis=set([start])
while q:
r,c=q.pop()
for dr,dc in dirs:
rr,cc=r+dr,c+dc
if 0<=rr<lim and 0<=cc<lim and (rr,cc) not in block and (rr,cc) not in vis:
if abs(rr-start[0])+abs(cc-start[1])>len(blocked): return True
vis.add((rr,cc))
q.append((rr,cc))
return False
return can_escape(tuple(source)) and can_escape(tuple(target))
s=Solution()
print(s.isEscapePossible(blocked = [[0,1],[1,0]], source = [0,0], target = [0,2]))
print(s.isEscapePossible(blocked = [], source = [0,0], target = [999999,999999]))