这个题的关键,就是用一个deque 来纪录蛇🐍的身体,然后用一个hash table 来判断蛇会不会撞到自己的身体然后死掉
C++ 代码
class SnakeGame {
private:
int width;
int height;
int foodIdx;
vector<pair<int, int>> food;
unordered_set<int> map;
deque<pair<int, int>> snake;
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]. */
SnakeGame(int width, int height, vector<pair<int, int>> food) {
this->width = width;
this->height = height;
foodIdx = 0;
this->food = food;
map.insert(0);
snake.push_back(pair<int, int>(0, 0));
}
/** 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) {
int dx = 0;
int dy = 0;
if (direction == "U"){
dx = -1;
}
else if (direction == "D"){
dx = 1;
}
else if (direction == "L"){
dy = -1;
}
else{
dy = 1;
}
int x = snake.back().first + dx;
int y = snake.back().second + dy;
if (x>=0 && x < height && y >= 0 && y < width){
snake.push_back(pair<int, int>(x, y));
if (foodIdx < food.size() && pair<int, int>(x, y) == food[foodIdx]){
foodIdx++;
}
else{
map.erase(snake.front().first*width + snake.front().second);
snake.pop_front();
}
if (map.count(x*width + y)){
return -1;
}
else{
map.insert(x*width + y);
}
return foodIdx;
}
else{
return -1;
}
}
};