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的更多相关文章

  1. [LeetCode] Design Snake Game 设计贪吃蛇游戏

    Design a Snake game that is played on a device with screen size = width x height. Play the game onli ...

  2. [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 ...

  3. LeetCode Design TinyURL

    原题链接在这里:https://leetcode.com/problems/design-tinyurl/description/ 题目: How would you design a URL sho ...

  4. [LeetCode] Design Phone Directory 设计电话目录

    Design a Phone Directory which supports the following operations: get: Provide a number which is not ...

  5. [LeetCode] Design Hit Counter 设计点击计数器

    Design a hit counter which counts the number of hits received in the past 5 minutes. Each function a ...

  6. [LeetCode] Design Twitter 设计推特

    Design a simplified version of Twitter where users can post tweets, follow/unfollow another user and ...

  7. [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 ...

  8. LeetCode Design Hit Counter

    原题链接在这里:https://leetcode.com/problems/design-hit-counter/. 题目: Design a hit counter which counts the ...

  9. [LeetCode] Design Search Autocomplete System 设计搜索自动补全系统

    Design a search autocomplete system for a search engine. Users may input a sentence (at least one wo ...

随机推荐

  1. myBaties 和 mysql开发中遇到的问题

    最近开发内部平台遇到mysql 中的一个问题,order by语句需要在limit 之后. myBaties在parameterType="java.lang.String" 不能 ...

  2. 表单验证——jquery validate使用说明【另一个教程】

    [参考:http://www.tuicool.com/articles/y6fyme] jQuery Validate jQuery Validate 插件为表单提供了强大的验证功能,让客户端表单验证 ...

  3. 疯狂房价"逼死"年轻人,别指望中国未来能出人才了

    社会高房价,杀死那个学者 --北京青年学者生存侧记 这一轮,房价又上涨了,只有更疯狂. 几年前,北京三环内的房价突破5万,世人惊呼:没几年,四环5万了,五环5万了:这一轮,北京城乡结合部,哪怕脏乱差之 ...

  4. CocoaPods安装和使用

    CocoaPods是iOS最常用的第三方类库管理工具,绝大部分有名的开源类库都支持CocoaPods. CocoaPods是用Ruby实现的,要想使用它首先需要有Ruby的环境.幸运的是OS X系统默 ...

  5. R实现灰色预测

    1.简介 预测就是借助于对过去的探讨去推测.了解未来.灰色预测通过原始数据的处理和灰色模型的建立,发现.掌握系统发展规律,对系统的未来状态做出科学的定量预测.对于一个具体的问题,究竟选择什么样的预测模 ...

  6. Hibernate和IBatis对比

    [转自]http://blog.csdn.net/ya2dan/article/details/7396598 项目也做过几个, 使用IBatis就做一个项目, 基本上都是使用Hibernate, 也 ...

  7. Leetcode Merge Intervals

    Given a collection of intervals, merge all overlapping intervals. For example,Given [1,3],[2,6],[8,1 ...

  8. [深入浅出WP8.1(Runtime)]Windows Phone 8.1和Silverlight 8.1的区别

    1.2.2 Windows Phone 8.1应用程序模型 Windows Phone 8.1支持多种开发语言来开发应用程序,包括C#.VB.JavaScript和C++,那么本书的代码主要是采用C# ...

  9. java 正则表达式

    1.首先是说明一些容易混淆的符号 \w    Matches any word character. \W    Matches any non-word character. 如果是在java中的话 ...

  10. MySQL查询语句(select)详解(1)

    1.查询记录 select*from 表名 [where 条件];eg:select*from students;//查询 students 表中所有记录,所有字段的值都显示出来select fiel ...