# Escape The Ghosts in C++

C++Server Side ProgrammingProgramming

Suppose we are playing a simplified Pacman game. Now we start at the point (0, 0), and our destination is (target, target). There are several ghosts on the map, Here the i-th ghost starts at (ghosts[i], ghosts[i]). In each turn, we and all ghosts simultaneously (may) move in one of 4 cardinal directions − north, east, west, or south, going from the last point to a new point 1 unit of distance away. We can escape if and only if we can reach the target before any ghost reaches us (for any given moves the ghosts may take.) If we reach any square (including the target) at the same time as a ghost, it doesn't count as an escape. So we have to return True when it is possible to escape.

So if the input is like [[1,0], [0,3]], and the target is [0,1], then result will be true. This is because we 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 us.

To solve this, we will follow these steps −

• me := |target| + |target|
• x := 0
• for i in range 0 to size of ghost array – 1
• x := |ghosts[i,0] – target| + |ghosts[i, 1] – target|
• if x <= me, then return false
• return true

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {
int me = abs(target) + abs(target);
int x = 0;
for(int i = 0; i < ghosts.size(); i++){
x = abs(ghosts[i] - target) + abs(ghosts[i] - target);
if(x <= me) return false;
}
return true;
}
};
main(){
vector<vector<int>> v1 = {{1,0}, {0,3}};
vector<int> v2 = {0,1};
Solution ob;
cout << (ob.escapeGhosts(v1, v2));
}

## Input

[[1,0],[0,3]]
[0,1]

## Output

1