Leetcode 789. Escape The Ghosts
You are playing a simplified PAC-MAN game. You start at the point (0, 0)
on an infinite 2D grid and your destination is the point target
. There are several ghosts on the same 2D grid, each represented as a point in a 2D array ghosts
. Each turn, you and all the ghosts may independently choose to move either north, south, east, or west by one unit.
You escape if and only if you can reach the target before any ghost can reach you. If you reach the target at the same time as a ghost, it is considered that the ghost catches you.
Return true
if it is possible to escape all ghosts or false
otherwise.
ghosts = [[1, 0], [0, 3]], target = [0, 1]
Output: true
ghosts = [[1, 0]], target = [2, 0]
false
(0, 0)
to the target is simply the Manhattan distance: |target[0]| + |target[1]|
.(0, 0)
.Here’s how we can implement this logic in C++:
#include <vector>
#include <cmath>
using namespace std;
class Solution {
public:
bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {
// Calculate the distance from the start point (0, 0) to the target
int playerDistance = abs(target[0]) + abs(target[1]);
// Check each ghost's distance to the target
for (const auto& ghost : ghosts) {
int ghostDistance = abs(ghost[0] - target[0]) + abs(ghost[1] - target[1]);
if (ghostDistance <= playerDistance) {
// If any ghost can reach the target at the same time or faster, you can't escape
return false;
}
}
// If no ghosts can reach the target faster or at the same time, you can escape
return true;
}
};
This solution efficiently determines if you can escape from all ghosts based on their distances to the target relative to yours.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?