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[0], target[1]). There are several ghosts on the map, Here the i-th ghost starts at (ghosts[i][0], ghosts[i][1]). 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[1]| + |target[0]|
  • x := 0
  • for i in range 0 to size of ghost array – 1
    • x := |ghosts[i,0] – target[0]| + |ghosts[i, 1] – target[1]|
    • if x <= me, then return false
  • return true

Let us see the following implementation to get better understanding −


 Live Demo

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




Published on 04-May-2020 17:44:58