离散化
逃离大迷宫
from typing import List
from bisect import insort, bisect_left
from collections import deque
MOVE = {(1, 0), (0, 1), (-1, 0), (0, -1)}
class Solution:
def isEscapePossible(self, blocked: List[List[int]], source: List[int], target: List[int]) -> bool:
if not blocked:
return True
x_all_nums = [0, source[0], 999999]
y_all_nums = [0, source[1], 999999]
for x, y in blocked:
insort(x_all_nums, x)
insort(y_all_nums, y)
insort(x_all_nums, target[0])
insort(y_all_nums, target[1])
x_all_nums = self.unique(x_all_nums)
y_all_nums = self.unique(y_all_nums)
ns = (bisect_left(x_all_nums, source[0]), bisect_left(y_all_nums, source[1]))
nt = (bisect_left(x_all_nums, target[0]), bisect_left(y_all_nums, target[1]))
nbs = {(bisect_left(x_all_nums, x), bisect_left(y_all_nums, y)) for x, y in blocked}
dq = deque()
dq.append(ns)
mark = {ns, }
while dq:
a, b = dq.popleft()
for x, y in MOVE:
x += a
y += b
if not (0 <= x < len(x_all_nums) and 0 <= y < len(y_all_nums)) or (x, y) in mark or (x, y) in nbs:
continue
if x == nt[0] and y == nt[1]:
return True
dq.append((x, y))
mark.add((x, y))
return False
def unique(self, nums):
if not nums:
return nums
ans = [nums[0]]
for num in nums[1:]:
if num != ans[-1]:
ans.append(num)
return ans求区域的个数

样例输入

离散化结果

离散化实现
最后更新于