C++ solution. Seems test case didn't consider food on body.


  • 0
    Y
    class SnakeGame { 
    public:
        /** Initialize your data structure here.
            @param width - screen width
            @param height - screen height 
            @param food - A list of food positions
            E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */
        vector<pair<int, int> > snake;
        vector<pair<int, int> > food;
        bool gameOver;
        int width;
        int height;
        int score;
        SnakeGame(int width, int height, vector<pair<int, int>> food) {
            score = 0;
            snake.emplace_back(0, 0);
            gameOver = false;
            this->width = width;
            this->height = height;
            this->food = food;
        }
        
        /** Moves the snake.
            @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down 
            @return The game's score after the move. Return -1 if game over. 
            Game over when snake crosses the screen boundary or bites its body. */
        int move(string direction) {
            if(gameOver) return -1;
            auto head = snake.front();
            auto tail = snake.back();
            snake.pop_back();
            switch(direction[0]) {
                case 'U': head.first--;break;
                case 'L': head.second--;break;
                case 'R': head.second++;break;
                case 'D': head.first++;break;
            }
            if(find(snake.begin(), snake.end(), head) != snake.end() || 
                head.first < 0 ||
                head.first >= height ||
                head.second < 0 ||
                head.second >= width) {
                gameOver = true;
                return -1;
            }
            snake.insert(snake.begin(), head);
            if(!food.empty() && head == food.front()) {
                food.erase(food.begin());
                snake.push_back(tail);
                score++;
            }
            return score;
        }
    };
    
    /**
     * Your SnakeGame object will be instantiated and called as such:
     * SnakeGame obj = new SnakeGame(width, height, food);
     * int param_1 = obj.move(direction);
     */

  • 0

    The problem description mentions:

    When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake.


  • 0
    Y

    Sorry. Didn't notice that sentence


Log in to reply
 

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