C++ queue with comments, beats 100%, 132ms


  • 0
    Z
    class SnakeGame {
    private:
        vector<pair<int, int>> food;
        vector<pair<int, int>> q;
        int w, h, pos, cx, cy;
    public:
    
        SnakeGame(int width, int height, vector<pair<int, int>> food) {
            this->food = food; w = width; h = height, pos = 0;
            // intially at [0][0]
            q.push_back({0, 0});
            cx = 0; cy = 0;
        }
        
        int move(string direction) {
            // New snake head position
            if (direction == "U") cx--;
            else if (direction == "L") cy--;
            else if (direction == "R") cy++;
            else if (direction == "D") cx++;
            
            // Out of bound check
            if (cx < 0 || cx >= h || cy < 0 || cy >= w) return -1;
            
            // check if there is food at new position
            if (pos < food.size() && food[pos].first == cx && food[pos].second == cy) pos++;
            else {
                // remove tail of snake
                q.erase(q.begin());
                // check if new head is already part of snake body
                for(pair<int, int>  &p: q)
                    if (p == make_pair(cx, cy))
                        return -1;
            }
            // push new head position to queue
            q.push_back({cx, cy});
            return q.size() - 1;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.