Design Snake Game Posted on 2018-10-13 Descriptionhttps://leetcode.com/problems/design-snake-game/description/ Solution123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566class SnakeGame {private: // vector<vector<int>> grid; int headX; int headY; int count; int height; int width; queue<pair<int, int>> que; unordered_map<string, pair<int, int>> directions; map<pair<int, int>, bool> occupied; vector<pair<int, int>> foods;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) { // vector<vector<int>> newGrid(height, vector<int>(width)); // grid = newGrid; directions["R"] = make_pair(0, 1); directions["L"] = make_pair(0, -1); directions["U"] = make_pair(-1, 0); directions["D"] = make_pair(1, 0); this->height = height; this->width = width; headX = 0; headY = 0; que.push(make_pair(headX, headY)); occupied[make_pair(headX, headY)] = true; count = 0; foods = 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) { int newX = headX + directions[direction].first; int newY = headY + directions[direction].second; //Hit the wall if (newX < 0 || newX >= height || newY < 0 || newY >= width) return -1; //Pay attention to the order of push and pop, we should try pop(shorten) the snake befroe we push pos into it. if (count < foods.size() && newX == foods[count].first && newY == foods[count].second) count += 1; else { pair<int, int> erase = que.front(); que.pop(); occupied.erase(erase); } if (occupied.count(make_pair(newX, newY)) != 0) return -1; //Hit itself occupied[make_pair(newX, newY)] = true; que.push(make_pair(newX, newY)); headX = newX; headY = newY; return count; }};