Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 5eb29ff

Browse files
Escape-The-Ghosts.js (ignacio-chiazzo#23)
1 parent 62fe628 commit 5eb29ff

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

LeetcodeProblems/Escape-The-Ghosts.js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/*
2+
https://leetcode.com/problems/escape-the-ghosts/description/
3+
4+
789. Escape The Ghosts
5+
6+
You are playing a simplified Pacman game. You start at the point (0, 0), and your destination is (target[0], target[1]). There are several ghosts on the map, the i-th ghost starts at (ghosts[i][0], ghosts[i][1]).
7+
8+
Each turn, you and all ghosts simultaneously *may* move in one of 4 cardinal directions: north, east, west, or south, going from the previous point to a new point 1 unit of distance away.
9+
10+
You escape if and only if you can reach the target before any ghost reaches you (for any given moves the ghosts may take.) If you reach any square (including the target) at the same time as a ghost, it doesn't count as an escape.
11+
12+
Return True if and only if it is possible to escape.
13+
14+
Example 1:
15+
Input:
16+
ghosts = [[1, 0], [0, 3]]
17+
target = [0, 1]
18+
Output: true
19+
Explanation:
20+
You 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 up with you.
21+
Example 2:
22+
Input:
23+
ghosts = [[1, 0]]
24+
target = [2, 0]
25+
Output: false
26+
Explanation:
27+
You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
28+
Example 3:
29+
Input:
30+
ghosts = [[2, 0]]
31+
target = [1, 0]
32+
Output: false
33+
Explanation:
34+
The ghost can reach the target at the same time as you.
35+
Note:
36+
37+
All points have coordinates with absolute value <= 10000.
38+
The number of ghosts will not exceed 100.
39+
*/
40+
41+
/**
42+
* @param {number[][]} ghosts
43+
* @param {number[]} target
44+
* @return {boolean}
45+
*/
46+
var escapeGhosts = function(ghosts, target) {
47+
var minDistanceGhost = Number.POSITIVE_INFINITY;
48+
for(ghost in ghosts) {
49+
const distance = getDistance(ghosts[ghost], target);
50+
if(distance < minDistanceGhost) {
51+
minDistanceGhost = distance;
52+
}
53+
}
54+
55+
var distancePacman = getDistance([0,0], target);
56+
return distancePacman < minDistanceGhost;
57+
};
58+
59+
var getDistance = function(a, b) {
60+
const horizontalMoves = Math.abs(a[0] - b[0]);
61+
const verticalMoves = Math.abs(a[1] - b[1]);
62+
return horizontalMoves + verticalMoves;
63+
}
64+
65+
var main = function() {
66+
console.log(escapeGhosts([[1, 0], [0, 3]], [0, 1]));
67+
console.log(escapeGhosts([[1, 0]], [2, 0]));
68+
console.log(escapeGhosts([[2, 0]], [1, 0]));
69+
}
70+
71+
module.exports.main = main

0 commit comments

Comments
 (0)