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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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