日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 353. 贪吃蛇(deque+set)

發(fā)布時間:2024/7/5 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 353. 贪吃蛇(deque+set) 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. 題目
    • 2. 解題

1. 題目

請你設計一個 貪吃蛇游戲,該游戲將會在一個 屏幕尺寸 = 寬度 x 高度 的屏幕上運行。

起初時,蛇在左上角的 (0, 0) 位置,身體長度為 1 個單位。

你將會被給出一個 (行, 列) 形式的食物位置序列。當蛇吃到食物時,身子的長度會增加 1 個單位得分也會 +1。

食物不會同時出現(xiàn),會按列表的順序逐一顯示在屏幕上。比方講,第一個食物被蛇吃掉后,第二個食物才會出現(xiàn)。

當一個食物在屏幕上出現(xiàn)時,它被保證不能出現(xiàn)在被蛇身體占據(jù)的格子里。

對于每個 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"); -> 函數(shù)返回 0| |S| | | | |F|snake.move("D"); -> 函數(shù)返回 0| | | | | |S|F|snake.move("R"); -> 函數(shù)返回 1 (蛇吃掉了第一個食物,同時第二個食物出現(xiàn)在位置 (0,1))| |F| | | |S|S|snake.move("U"); -> 函數(shù)返回 1| |F|S| | | |S|snake.move("L"); -> 函數(shù)返回 2 (蛇吃掉了第二個食物)| |S|S| | | |S|snake.move("U"); -> 函數(shù)返回 -1 (蛇與邊界相撞,游戲結束)

來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/design-snake-game
著作權歸領扣網(wǎng)絡所有。商業(yè)轉載請聯(lián)系官方授權,非商業(yè)轉載請注明出處。

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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。