Escape The Ghosts

medium math geometry manhattan-distance

Problem

You start at (0,0) and want to reach target. Ghosts start at given positions. Each turn everyone moves one step in any cardinal direction. Determine if you can reach target before any ghost catches you.

Inputghosts = [[1,0],[0,3]], target = [0,1]
Outputtrue
You reach target in 1 step; nearest ghost needs 2 steps.

def escapeGhosts(ghosts, target):
    my_dist = abs(target[0]) + abs(target[1])
    for g in ghosts:
        gd = abs(g[0] - target[0]) + abs(g[1] - target[1])
        if gd <= my_dist:
            return False
    return True
var escapeGhosts = function(ghosts, target) {
    const myDist = Math.abs(target[0]) + Math.abs(target[1]);
    for (const g of ghosts) {
        const gd = Math.abs(g[0] - target[0]) + Math.abs(g[1] - target[1]);
        if (gd <= myDist) return false;
    }
    return true;
};
class Solution {
    public boolean escapeGhosts(int[][] ghosts, int[] target) {
        int myDist = Math.abs(target[0]) + Math.abs(target[1]);
        for (int[] g : ghosts) {
            int gd = Math.abs(g[0] - target[0]) + Math.abs(g[1] - target[1]);
            if (gd <= myDist) return false;
        }
        return true;
    }
}
class Solution {
public:
    bool escapeGhosts(vector<vector<int>>& ghosts, vector<int>& target) {
        int myDist = abs(target[0]) + abs(target[1]);
        for (auto& g : ghosts) {
            int gd = abs(g[0] - target[0]) + abs(g[1] - target[1]);
            if (gd <= myDist) return false;
        }
        return true;
    }
};
Time: O(g) Space: O(1)