← Static tasks

789. Escape The Ghosts

leetcode

#array#csharp#leetcode#math

Task

: medium

Вы играете в упрощенную игру PAC-MAN на бесконечной 2D-сетке. Вы начинаете в точке [0, 0], и у вас есть конечная точка target = [xtarget, ytarget], к которой вы пытаетесь добраться. На карте находятся несколько привидений, их начальные позиции заданы в виде двумерного массива ghosts, где ghosts[i] = [xi, yi] представляет начальную позицию i-го привидения. Все входные данные являются целочисленными координатами.

Каждый ход вы и все привидения можете независимо выбирать перемещение на 1 единицу в любом из четырех основных направлений: север, восток, юг или запад, или оставаться на месте. Все действия происходят одновременно.

Вы сможете сбежать, если и только если сможете достичь цели раньше, чем любое привидение достигнет вас. Если вы достигнете любой клетки (включая конечную точку) одновременно с привидением, это не считается побегом.

Верните true, если можно сбежать независимо от того, как движутся привидения, иначе верните false.

Пример:

Input: ghosts = [[1,0],[0,3]], target = [0,1]

Output: true

Explanation: You can reach the destination (0, 1) after 1 turn, while the ghosts located at (1, 0) and (0, 3) cannot catch up with you.

C# solution

matched/original
public class Solution {
    public bool EscapeGhosts(int[][] ghosts, int[] target) {
        int playerDistance = Taxi(new int[] {0, 0}, target);
        foreach (var ghost in ghosts) {
            if (Taxi(ghost, target) <= playerDistance) {
                return false;
            }
        }
        return true;
    }
    private int Taxi(int[] P, int[] Q) {
        return Math.Abs(P[0] - Q[0]) + Math.Abs(P[1] - Q[1]);
    }
}

C++ solution

auto-draft, review before submit
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    public bool EscapeGhosts(int[][] ghosts, vector<int>& target) {
        int playerDistance = Taxi(new int[] {0, 0}, target);
        foreach (var ghost in ghosts) {
            if (Taxi(ghost, target) <= playerDistance) {
                return false;
            }
        }
        return true;
    }
    private int Taxi(vector<int>& P, vector<int>& Q) {
        return abs(P[0] - Q[0]) + abs(P[1] - Q[1]);
    }
}

Java solution

auto-draft, review before submit
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
    public boolean EscapeGhosts(int[][] ghosts, int[] target) {
        int playerDistance = Taxi(new int[] {0, 0}, target);
        foreach (var ghost in ghosts) {
            if (Taxi(ghost, target) <= playerDistance) {
                return false;
            }
        }
        return true;
    }
    private int Taxi(int[] P, int[] Q) {
        return Math.abs(P[0] - Q[0]) + Math.abs(P[1] - Q[1]);
    }
}

Python solution

matched/original
class Solution:
    def escapeGhosts(self, ghosts, target):
        def taxi(P, Q):
            return abs(P[0] - Q[0]) + abs(P[1] - Q[1])

        return all(taxi([0, 0], target) < taxi(ghost, target)
                   for ghost in ghosts)

Go solution

matched/original
package main

import "math"

func escapeGhosts(ghosts [][]int, target []int) bool {
    taxi := func(P, Q []int) int {
        return int(math.Abs(float64(P[0] - Q[0])) + math.Abs(float64(P[1] - Q[1])))
    }

    playerDistance := taxi([]int{0, 0}, target)
    for _, ghost := range ghosts {
        if taxi(ghost, target) <= playerDistance {
            return false
        }
    }
    return true
}

Explanation

Algorithm

1⃣Проверьте, что наше таксическое расстояние до цели меньше, чем расстояние от любого привидения до цели.

2⃣Если это так, мы можем гарантированно добраться до цели раньше любого привидения.

3⃣Если привидение может добраться до цели раньше нас или одновременно с нами, побег невозможен.

😎