Leetcode: Design Snake Game
Design a Snake game that is played on a device with screen size = width x height. Play the game online if you are not familiar with the game. The snake is initially positioned at the top left corner (0,0) with length = 1 unit. You are given a list of food's positions in row-column order. When a snake eats the food, its length and the game's score both increase by 1. Each food appears one by one on the screen. For example, the second food will not appear until the first food was eaten by the snake. When a food does appear on the screen, it is guaranteed that it will not appear on a block occupied by the snake. Example:
Given width = 3, height = 2, and food = [[1,2],[0,1]]. Snake snake = new Snake(width, height, food); Initially the snake appears at position (0,0) and the food at (1,2). |S| | |
| | |F| snake.move("R"); -> Returns 0 | |S| |
| | |F| snake.move("D"); -> Returns 0 | | | |
| |S|F| snake.move("R"); -> Returns 1 (Snake eats the first food and right after that, the second food appears at (0,1) ) | |F| |
| |S|S| snake.move("U"); -> Returns 1 | |F|S|
| | |S| snake.move("L"); -> Returns 2 (Snake eats the second food) | |S|S|
| | |S| snake.move("U"); -> Returns -1 (Game over because snake collides with border)
HashSet + Queue:
吃东西的时候保留尾巴,不吃的时候删去尾巴
one case to notice蛇转弯的时候,要先删去尾巴,再把新的点加进去。如果这个顺序不对的话,本来不会撞上尾巴的结果会判断会撞上
public class SnakeGame {
int m;
int n;
int[][] foods;
Queue<Integer> queue;
HashSet<Integer> set;
int[] headPos;
int foodSeq;
/** 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]. */
public SnakeGame(int width, int height, int[][] food) {
this.m = height;
this.n = width;
this.foods = food;
this.queue = new LinkedList<Integer>();
this.set = new HashSet<Integer>();
this.headPos = new int[]{0, 0};
this.foodSeq = 0;
queue.offer(0);
set.add(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. */
public int move(String direction) {
int[] dir;
switch(direction) {
case "U": dir = new int[]{-1, 0}; break;
case "L": dir = new int[]{0, -1}; break;
case "R": dir = new int[]{0, 1}; break;
case "D": dir = new int[]{1, 0}; break;
default: dir = new int[2];
}
int row = headPos[0] + dir[0]; // new position row
int col = headPos[1] + dir[1]; // new position col
//delete tail first, before push into a new cell
if (foodSeq<foods.length && calcPosId(foods[foodSeq][0], foods[foodSeq][1]) == calcPosId(row, col)) {
foodSeq++;
}
else {
set.remove(queue.poll());
}
if (row<0 || row>=m || col<0 || col>=n) return -1; // hit border
if (set.contains(calcPosId(row, col))) return -1; // hit its own body
set.add(calcPosId(row, col));
queue.offer(calcPosId(row, col));
headPos[0] = row;
headPos[1] = col;
return set.size()-1;
}
public int calcPosId(int x, int y) {
return x*n+y;
}
}
/**
* Your SnakeGame object will be instantiated and called as such:
* SnakeGame obj = new SnakeGame(width, height, food);
* int param_1 = obj.move(direction);
*/
如果没有39行,程序会说dir没有initialize,
其实更好的写法应该是
int rowHead = body.peekFirst() / width;
int colHead = body.peekFirst() % width;
switch (direction) {
case "U" : rowHead--;
break;
case "D" : rowHead++;
break;
case "L" : colHead--;
break;
default : colHead++;
}
Leetcode: Design Snake Game的更多相关文章
- [LeetCode] Design Snake Game 设计贪吃蛇游戏
Design a Snake game that is played on a device with screen size = width x height. Play the game onli ...
- [Swift]LeetCode353. 设计贪吃蛇游戏 $ Design Snake Game
Design a Snake game that is played on a device with screen size = width x height. Play the game onli ...
- LeetCode Design TinyURL
原题链接在这里:https://leetcode.com/problems/design-tinyurl/description/ 题目: How would you design a URL sho ...
- [LeetCode] Design Phone Directory 设计电话目录
Design a Phone Directory which supports the following operations: get: Provide a number which is not ...
- [LeetCode] Design Hit Counter 设计点击计数器
Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...
- [LeetCode] Design Twitter 设计推特
Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...
- [LeetCode] Design Tic-Tac-Toe 设计井字棋游戏
Design a Tic-tac-toe game that is played between two players on a n x n grid. You may assume the fol ...
- LeetCode Design Hit Counter
原题链接在这里:https://leetcode.com/problems/design-hit-counter/. 题目: Design a hit counter which counts the ...
- [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统
Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...
随机推荐
- iOS AFOAuth2Manager使用心得
github地址: https://github.com/AFNetworking/AFOAuth2Manager 这个库,不多说,实现OAuth 2.0授权访问. 确实可以减轻很大的负担,而且使用 ...
- Android入门(一):创建Android工程
开发Android应用过程一般分为三步: 1.创建一个Android工程: 2.在xml布局文件中定义应用所包含的控件: 3.在Java代码中实现业务逻辑. 此文就介绍第一部分,创建一个Android ...
- SpringMVC注解@RequestMapping全面解析---打酱油的日子
@RequestMapping 可以出现在类级别上,也可以出现在方法上.如果出现在类级别上,那请求的 url 为 类级别上的@RequestMapping + 方法级别上的 @RequestMappi ...
- 洛谷 P2737 [USACO4.1]麦香牛块Beef McNuggets Label:一点点数论 && 背包
题目描述 农夫布朗的奶牛们正在进行斗争,因为它们听说麦当劳正在考虑引进一种新产品:麦香牛块.奶牛们正在想尽一切办法让这种可怕的设想泡汤.奶牛们进行斗争的策略之一是“劣质的包装”.“看,”奶牛们说,“如 ...
- WebCrawler
WebCrawler WebCrawler is a metasearch engine that blends the top search results from Google Search a ...
- [代码]label增加删除线
UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(20, 60, 100, 30)]; [self.view addSubvi ...
- HDU 3743 Frosh Week (线段树+离散化)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3743 Frosh Week Time Limit : 2000/1000ms (Java/Other) ...
- 畅通工程——D
D. 畅通工程 省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可).经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的 ...
- Django视图与网址
Django中网址是写在 urls.py 文件中,用正则表达式对应 views.py 中的一个函数(或者generic类),我们用一个项目来演示. 下载本节所有源代码: 学习编程最好的办法就是动手敲代 ...
- Bean不同配置方式的比较
在<Spring3.x 企业应用开发实战>上学习了Bean的三种不同配置方法,下图是我从书中截取的图片,比较了一下这三种配置的异同 ps:发现图片不能完全显示(右侧有一块不显示),解决方法 ...