LeetCode 789. Escape The Ghosts
Posted sylvanyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 789. Escape The Ghosts相关的知识,希望对你有一定的参考价值。
题目链接:https://leetcode.com/problems/escape-the-ghosts/description/
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.
Example 1: Input: ghosts = [[1, 0], [0, 3]] target = [0, 1] Output: true Explanation: You can directly reach the destination (0, 1) at time 1, while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you.Example 2: Input: ghosts = [[1, 0]] target = [2, 0] Output: false Explanation: You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.Example 3: Input: ghosts = [[2, 0]] target = [1, 0] Output: false Explanation: The ghost can reach the target at the same time as you.Note:
- All points have coordinates with absolute value <=
10000
.- The number of ghosts will not exceed
100
.
这道题乍看之下有点摸不到头脑,而且很容易想到当年玩吃豆人的时候各种奇怪的corner case死法从而对题解想的过于复杂(比如DFS搜索解空间树什么的,可是想象一下每一个ghose每一步都可以有5个next state,要是有100个鬼就是TM 5^100 次方,做个P。。)。其实这道题很简单,因为ghose可以呆着不动,所以就可以直接奔着target走,如果能比你先到,那么就在target等着你就行,你就必输。所以归根结底就是算一下每一个ghose 到target的Manhattan Distance。如果比[0,0]到target的距离小,那就是False,反之则为True。要注意coordinate可能是负数,所以要加abs。代码很好写:
class Solution(object): def escapeGhosts(self, ghosts, target): """ :type ghosts: List[List[int]] :type target: List[int] :rtype: bool """ dist = abs(target[0]) + abs(target[1]) for x, y in ghosts: if abs(x-target[0]) + abs(y-target[1]) <= dist: return False return True
以上是关于LeetCode 789. Escape The Ghosts的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Escape The Ghosts 逃离鬼魂
Codeforces 789e The Great Mixing (bitset dp 数学)