789. Escape The Ghosts
- Escape The Ghosts python solution
题目描述
You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is (target[0], target[1]). There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]).
Each turn, you and all ghosts simultaneously may move in one of 4 cardinal directions: north, east, west, or south, going from the previous point to a new point 1 unit of distance away.
You escape if and only if you can reach the target before any ghost reaches you (for any given moves the ghosts may take.) If you reach any square (including the target) at the same time as a ghost, it doesn’t count as an escape.
Return True if and only if it is possible to escape.
解析
游戏的背景非常有趣,就是鬼魂能否抓到你。
有一种非常巧妙地解法,我其实不需要考虑鬼魂们离我有多近。如果鬼魂们可以先到达目标点,那么我们必输无疑。所以我和鬼魂也不需要玩猫捉老鼠的游戏,只需要看谁能更先到达目标点即可。
所以,只需要比较我和鬼魂们到重点的距离即可!
class Solution:
def escapeGhosts(self, ghosts: List[List[int]], target: List[int]) -> bool:
distance=abs(target[0])+abs(target[1])
for row,col in ghosts:
if abs(target[0]-row)+abs(target[1]-col)< distance:
return False
return True
Reference
https://leetcode.com/problems/escape-the-ghosts/discuss/116511/Short-with-explanation-python