- 题目:
https://leetcode-cn.com/problems/escape-the-ghosts/
一个玩家从 (0,0) 起步,另外若干个 ghosts 从 ghosts[] 起步
每个回合都可向上下左右任意方向走1步
输出:玩家能否躲避 ghost 到达 target
- 题解:
玩家能否躲避 ghost 到达 target
——等价于玩家到 target 步数比任意 ghost 到 target 步数要少
步数
——上下左右任意方向走1步,总步数就是Manhattan距离
- 代码:
class Solution:
def escapeGhosts(self, ghosts: list[list[int]], target: list[int]) -> bool:
def mdist(p, q):
return abs(p[0] - q[0]) + abs(p[1] - q[1])
t = mdist([0, 0], target)
for g in ghosts:
if mdist(g, target) <= t: return False
return True
if __name__ == "__main__":
print(Solution().escapeGhosts(ghosts = [[1,0],[0,3]], target = [0,1]))
print(Solution().escapeGhosts(ghosts = [[1,0]], target = [2,0]))
print(Solution().escapeGhosts(ghosts = [[2,0]], target = [1,0]))
print(Solution().escapeGhosts(ghosts = [[5,0],[-10,-2],[0,-5],[-2,-2],[-7,1]], target = [7,7]))
print(Solution().escapeGhosts(ghosts = [[-1,0],[0,1],[-1,0],[0,1],[-1,0]], target = [0,0]))