
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Escape The Ghosts in C++
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 −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: 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; } }; 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
- Related Articles
- The "" escape character in C#
- Escape sequences in C
- Ways to print escape characters in C#
- List down a list of the escape characters in C#
- What are the escape sequences supported by C#?
- Escape sequences in Java
- Escape Characters in Python
- Escape characters in JavaScript
- JavaScript escape()
- The Escape Velocity of Earth
- Build (escape) regexp in MongoDB?
- How to escape single quotes in MySQL?
- How to escape apostrophe (') in MySQL?
- Ways to print escape characters in python
- Unicode codepoint escape syntax in PHP 7
