You are playing a simplified PAC-MAN game. You start at the point (0, 0)
on an infinite 2D grid and your destination is at a specific point target
. There are several ghosts on the same 2D grid, each of whom start at different points and you want to reach the target without any ghost reaching it before you or at the same time.
Given an array ghosts
, where ghosts[i]
is an array [x_i, y_i] representing the starting position of the i-th ghost, and given the array target
of length 2 representing your destination:
You need to return True
if you can escape all the ghosts, otherwise return False
.
ghosts = [[1, 0], [0, 3]], target = [0, 1]
True
ghosts = [[1, 0]], target = [2, 0]
False
ghosts[i]
will be within the range [-10^4, 10^4]
.target
will be within the range [-10^4, 10^4]
.|target[0] - 0| + |target[1] - 0|
.|target[0] - ghost[i][0]| + |target[1] - ghost[i][1]|
.False
.True
.def escapeGhosts(ghosts, target):
# Calculate player's distance to the target
player_distance = abs(target[0]) + abs(target[1])
# Check each ghost's distance to the target
for ghost in ghosts:
ghost_distance = abs(target[0] - ghost[0]) + abs(target[1] - ghost[1])
if ghost_distance <= player_distance:
return False
return True
# Example usage
print(escapeGhosts([[1, 0], [0, 3]], [0, 1])) # Expected output: True
print(escapeGhosts([[1, 0]], [2, 0])) # Expected output: False
The time complexity for this solution is (O(n)), where (n) is the number of ghosts. This is because for each ghost, we perform a constant time calculation to compute the Manhattan distance and compare it. Thus, the solution is efficient and scales linearly with the number of ghosts.
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?