2021-8-22 Escape the Ghosts

难度 中等

题目 Leetcode:

You are playing a simplified PAC-MAN game on an infinite 2-D grid. You start at the point [0, 0], and you are given a destination point target = [xtarget, ytarget], which you are trying to get to. There are several ghosts on the map with their starting positions given as an array ghosts, where ghosts[i] = [xi, yi] represents the starting position of the ith ghost. All inputs are integral coordinates.

Each turn, you and all the ghosts may independently choose to either move 1 unit in any of the four cardinal directions: north, east, south, or west or stay still. All actions happen simultaneously.

You escape if and only if you can reach the target before any ghost reaches you. If you reach any square (including the target) at the same time as a ghost, it does not count as an escape.

Return true if it is possible to escape, otherwise return false.

 

题目解析

本题的大意就是人从(0,0)出发到达( x , y ),但是会有若干人前来阻截,他们会分别从各自的起点出发。如果没人阻截成功就返回true,反之false。

这样一题的思路我从一开始就想复杂了,这题用到的更多的是数学上的思考,也就是将问题数学化。

也即一点从(0,0)出发到(x,y),其余若干点如果存在一点到达(x,y)所需要的距离小于第一点,那么就绝对能够阻截成功。

解析完毕,以下是参考代码

1 class Solution {
2 public:
3     bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {
4         int dis = abs(target[0]) + abs(target[1]);
5         for(auto &it: ghosts)
6             if(abs(it[0]-target[0]) + abs(it[1]-target[1]) <= dis)return false;
7         return true;
8     }
9 };

 

2021-8-22 Escape the Ghosts

上一篇:[CentOS7]rar


下一篇:打开服务器的文档