Sponsored
Sponsored
This approach calculates the Manhattan distance from the starting point (0,0) to the target for you, and for each ghost from their starting position to the target. You can only escape if your distance to the target is strictly less than every ghost's distance to the target, meaning you reach the destination before any ghost can get there.
Time Complexity: O(n), where n is the number of ghosts. Space Complexity: O(1).
1#include <stdbool.h>
2#include <stdlib.h>
3
4int manhattanDistance(int x1, int y1, int x2, int y2) {
5 return abs(x1 - x2) + abs(y1 - y2);
6}
7
8bool escapeGhosts(int** ghosts, int ghostsSize, int* ghostsColSize, int* target, int targetSize) {
9 int playerDistance = manhattanDistance(0, 0, target[0], target[1]);
10 for (int i = 0; i < ghostsSize; i++) {
11 int ghostDistance = manhattanDistance(ghosts[i][0], ghosts[i][1], target[0], target[1]);
12 if (ghostDistance <= playerDistance) {
13 return false;
14 }
15 }
16 return true;
17}
This C code defines a function to calculate the Manhattan distance and checks if you can escape by comparing your distance to the target with each ghost's distance.
This approach involves simulating every possible move for you and each ghost simultaneously. For each time step, move each entity towards the target or keep them in the same position if they're already there. This approach is generally inefficient but illustrates the problem space.
Time Complexity: O(n), where n is the number of ghosts. Space Complexity: O(1).
1class
The function in Python approximates brute force by comparing distances. True simulation is impractical for performance reasons.