leetcode 789. Escape The Ghosts

leetcode 789. Escape The Ghosts

题目描述

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.

Note:

  • All points have coordinates with absolute value <= 10000.
  • The number of ghosts will not exceed 100.

Difficulty: medium
789. Escape The Ghosts


中文描述
你从(0, 0)位置出发,需要到达目的地(target[0], target[1]),不过周围有许多鬼魂,你和它们每次可以向4个方向移动一格,问你是否能在被鬼魂碰到之前到达目的地,同时到达也不算逃脱成功。


输入格式
输入一个列表ghosts,列表鬼魂所在的位置。target表示你需要到达的目的地。


Examples:

  1. Input: ghosts = [[1, 0], [0, 3]],target = [0, 1]
    Output: true
    解释:
    你只用向右走一步就能到达,而鬼魂最少需要两步才能碰到你。所以你可以逃脱

  2. Input: ghosts = [[1, 0]], target = [2, 0]
    Output: false
    解释:
    鬼魂拦在你和目的地之间,你无法成功越过它到达目的地。所以无法逃脱。

  3. Input: ghosts = [[2, 0]],target = [1, 0]
    Output: false
    解释:
    鬼魂能和你同时到达目的地。所以无法逃脱。


解答思路

  • 这题看上去很难,感觉可能需要遍历所有的情况才能找到最后的答案。然而却并不需要。考虑下第二个案例,为何鬼魂拦在我们和目的地之间,我们就无法顺利到达?如果考虑我们始终选择最短路径到达目的地(因为如果我们不选择最短路径,则鬼魂的移动范围则会增加),则鬼魂也可以选择最短路径去目标处埋伏你。所以问题就转化为,你到达目的地的最快速度,是否能比鬼魂快。这样这道题就很好解答了。至于为什么鬼魂不再中途拦截,可以看下这篇文章的解释Why interception in the middle is not a good idea for ghosts.或则我们考虑个极端点的情况,如果鬼魂能比你更快的到达目的地,则它可以一直在目的地蹲守,这样无论如何你都不能逃脱(题目只说可以向4个方向移动,没说必须移动,感觉如果是必须移动,这题就很麻烦了)。估计这题太trick,差评很多= =。

代码

很简单的代码,就不附带说明了

class Solution(object):
    def escapeGhosts(self, ghosts, target):
        """
        :type ghosts: List[List[int]]
        :type target: List[int]
        :rtype: bool
        53MS
        """
        l = [abs(target[0] - ghost[0]) + abs(target[1] - ghost[1]) for ghost in ghosts]
        d = abs(target[0] - 0) + abs(target[1] - 0)
        if d < min(l):
            return True
        else:
            return False

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值