LeetCode 353. 贪吃蛇(deque+set)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 353. 贪吃蛇(deque+set)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
請你設計一個 貪吃蛇游戲,該游戲將會在一個 屏幕尺寸 = 寬度 x 高度 的屏幕上運行。
起初時,蛇在左上角的 (0, 0) 位置,身體長度為 1 個單位。
你將會被給出一個 (行, 列) 形式的食物位置序列。當蛇吃到食物時,身子的長度會增加 1 個單位,得分也會 +1。
食物不會同時出現,會按列表的順序逐一顯示在屏幕上。比方講,第一個食物被蛇吃掉后,第二個食物才會出現。
當一個食物在屏幕上出現時,它被保證不能出現在被蛇身體占據的格子里。
對于每個 move() 操作,你需要返回當前得分或 -1(表示蛇與自己身體或墻相撞,意味游戲結束)。
示例:給定 width = 3, height = 2, 食物序列為 food = [[1,2],[0,1]]。Snake snake = new Snake(width, height, food);初始時,蛇的位置在 (0,0) 且第一個食物在 (1,2)。|S| | | | | |F|snake.move("R"); -> 函數返回 0| |S| | | | |F|snake.move("D"); -> 函數返回 0| | | | | |S|F|snake.move("R"); -> 函數返回 1 (蛇吃掉了第一個食物,同時第二個食物出現在位置 (0,1))| |F| | | |S|S|snake.move("U"); -> 函數返回 1| |F|S| | | |S|snake.move("L"); -> 函數返回 2 (蛇吃掉了第二個食物)| |S|S| | | |S|snake.move("U"); -> 函數返回 -1 (蛇與邊界相撞,游戲結束)來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/design-snake-game
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class SnakeGame {vector<vector<int>> food;int m, n, i = 0, score = 0;int x = 0, y = 0;unordered_map<string, vector<int>> dir;deque<pair<int,int>> body;set<pair<int,int>> body_set; public:/** Initialize your data structure here.@param width - screen width@param height - screen height @param food - A list of food positionsE.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<vector<int>>& food) {this->food = food;n = width;m = height;dir["R"] = {0,1};dir["D"] = {1,0};dir["U"] = {-1,0};dir["L"] = {0,-1};body.push_back({0,0});body_set.insert({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) {x += dir[direction][0];y += dir[direction][1];if(!(x>=0 && x<m && y>=0 && y<n)) return -1;//出界if(i < food.size() && x == food[i][0] && y == food[i][1]){ //吃到食物body.push_front({x, y});//頭部加上body_set.insert({x, y});i++;score++;}else//沒吃到{pair<int,int> tail = body.back();body_set.erase(tail);//刪除尾巴body.pop_back();//刪除尾巴body.push_front({x, y});//頭部加上if(body_set.count({x,y}))//撞身體了return -1;body_set.insert({x,y});//身體集合加入頭部}return score;} };364 ms 73.6 MB
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 353. 贪吃蛇(deque+set)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1631. 最小体力消
- 下一篇: LeetCode 1736. 替换隐藏数