Saturday, February 24, 2018

LeetCode 789. Escape The Ghosts - Weekly Contest 73

https://leetcode.com/contest/weekly-contest-73/problems/escape-the-ghosts/


Come to think of it, I realize no matter which location they are locating, the distance to the target is what really matters.

So naturally we come up with a helper function to getDistance,

then, naturally we will compare the distances and see if any ghosts are dangerously close.

That's it.





class Solution {
boolean escapeGhosts(int[][] ghosts, int[] target) {
// filter abnormal cases
// if (A == null || A.length == 0) {
// return 0;
// }
if (ghosts == null || ghosts.length == 0) {
return true;
}
int myDistance = getDistance(new int[]{0, 0}, target);
int m = ghosts.length;
for (int i = 0; i < m; i++) {
int tmpDistance = getDistance(ghosts[i], target);
if (tmpDistance <= myDistance) {
return false;
}
}
// return the final result
return true;
}
int getDistance(int[] source, int[] target) {
return Math.abs(source[0] - target[0]) + Math.abs(source[1] - target[1]);
}
}

No comments:

Post a Comment