C++ simple solution beat 91.80%


  • 0
    class SnakeGame {
    public:
        int width, height, index;
        vector<pair<int, int>> food, snake;
        SnakeGame(int width, int height, vector<pair<int, int>> food) : width(width), height(height) {
            this->food = food;
            this->snake.push_back({0, 0});
            index = 0;
        }
    
        int move(string direction) {
            pair<int, int> next;
            switch (direction[0]) {
                case 'U':
                    next = {snake[0].first - 1, snake[0].second};
                    break;
                case 'L':
                    next = {snake[0].first, snake[0].second - 1};
                    break;
                case 'R':
                    next = {snake[0].first, snake[0].second + 1};
                    break;
                case 'D':
                    next = {snake[0].first + 1, snake[0].second};
                    break;
                default :
                    return -1;
            }
            if (next.first < 0 || next.first >= height || next.second < 0 || next.second >= width) 
                return -1;
            if (index < food.size() && next == food[index]) { // get food
                index++;
                snake.insert(snake.begin(), next);
                return index;
            } else {
                int n = snake.size();
                for (int i = n - 1; i > 0; i--) {
                    if (next == snake[i] && i != n - 1) // eat self
                        return -1;
                    snake[i] = snake[i - 1];
                }
                snake[0] = next;
                return index;
            }
            
        }
    };

Log in to reply
 

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