Untitled

 avatar
unknown
c_cpp
10 months ago
1.7 kB
6
Indexable
class Solution {
public:

    struct hash_pair {
        template <class T1, class T2>
        size_t operator() (const pair<T1, T2>& p) const {
            auto hash1 = hash<T1>{}(p.first);
            auto hash2 = hash<T2>{}(p.second);
            return hash1 ^ hash2;
        }
    };

    void left(int &n, int &s, int &e, int &w) {
        if(n == 1)        w = 1, n = 0;
        else if(s == 1)   e = 1, s = 0;
        else if(e == 1)   n = 1, e = 0;
        else              s = 1, w = 0;
    }

    void right(int &n, int &s, int &e, int &w) {
        if(n == 1)        e = 1, n = 0;
        else if(s == 1)   w = 1, s = 0;
        else if(e == 1)   s = 1, e = 0;
        else              n = 1, w = 0;
    }

    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        int x = 0, y = 0;
        int n = 1, s = 0, e = 0, w = 0;

        unordered_map<pair<int, int>, int, hash_pair> mymap;
        for(auto obs : obstacles){
            mymap[{obs[0], obs[1]}] = 1;
        }
        int ans=INT_MIN;
        for(auto c : commands){
            if(c == -1)
                right(n, s, e, w);
            else if(c == -2)
                left(n, s, e, w);
            else {
                for(int i = 0; i < c; i++) {
                    if(n == 1 && !mymap.count({x, y + 1}))       y++;
                    else if(s == 1 && !mymap.count({x, y - 1}))  y--;
                    else if(e == 1 && !mymap.count({x + 1, y}))  x++;
                    else if(w == 1 && !mymap.count({x - 1, y}))  x--;
                    else break;
                }
            }
            ans=max(ans,x*x+y*y);
        }
        return ans;
    }
};
Editor is loading...
Leave a Comment