Straightforward code with list in C++


  • 0
    D

    I just use a list to keep track the snake. The trickiest thing is that the new position is checked against the body after the movement.

    class SnakeGame {

    public:
    SnakeGame(int width, int height, vector<pair<int, int>> food)
    : width_(width),
    height_(height),
    food_(food),
    cur_food_idx_(0),
    score_(0) {
    snake_.emplace_back(0,0);
    }

    int move(string direction) {
        if (direction.length() != 1)
            return -1;
        
        char d = direction[0];
        pair<int, int> shift;
        switch (d) {
            case 'U':
                shift = {-1,0};
                break;
            case 'L':
                shift = {0,-1};
                break;
            case 'R':
                shift = {0,1};
                break;
            case 'D':
                shift = {1,0};
                break;
            default:
                return -1;
        }
        Position new_position(Head());
        new_position.first += shift.first;
        new_position.second += shift.second;
    
        if (cur_food_idx_ >= food_.size() || new_position != food_[cur_food_idx_]) {
            snake_.pop_front();
        } else {
            ++cur_food_idx_;
            ++score_;
        }
        
        if (!IsValid(new_position) || Clash(new_position))
            return -1;
        snake_.emplace_back(new_position);
        return score_;
    } private:
    
    typedef pair<int, int> Position;
    Position Head() {
        return snake_.back();
    }
    
    bool IsValid(Position new_position) {
        return new_position.first < height_ && new_position.second < width_ && new_position.first >= 0 && new_position.second >= 0;
    }
    
    bool Clash(Position pos) {
        for (Position s : snake_) {
            if (pos.first == s.first && pos.second == s.second)
                return true;
        }
        return false;
    }
        
    void Print() {
        for (Position s : snake_) {
            cout << s.first << ',' << s.second << ' ';
        }
        cout << endl;
    }
    int width_, height_;
    vector<pair<int, int>> food_;
    list<pair<int, int>> snake_;
    int cur_food_idx_;
    int score_;
    

    };


Log in to reply
 

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