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 ...
随机推荐
- Json.Net的简单使用
1.添加程序集 Newtonsoft.Json.dll 2.创建模型 public class Person { public string Name { get; set; } public ...
- 说说 js String
首先说说js的字符串,说到字符串这个就和我们原来的C# 代码有区别的就是,js里面没有chart类型.就是说他里面的 “ ”和‘ ’是要表达一样的意思. 其实这个里面就有一个问题了特别实在拼接字符串的 ...
- java单例模式的几种写法比较
概念: Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单例类只能有一个实例. 2.单例类必须自己创建 ...
- Hibernate学习笔记5
hql语句的查询(hibernate query language) hql和sql语句的区别sql:语言关系型数据库里面的通用查询,结构化查询语言,查看的是表以及表的列hql是hibernate中独 ...
- Intersection of Two Linked Lists
Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...
- Web.xml各版本模版
web.xml v2.3 web.xml v2.4 <?xml version="1.0" encoding="UTF-8"?> <web-a ...
- Swift微博编写感
首先Swift是苹果2014年力推的编程语言.可见发展趋势 在此提供
- WPF整理-使用逻辑资源
"Traditional application resources consist of binary chunks of data, typically representing thi ...
- IE 6 ~ 9 CSS Hack 写法总结
IE 6 ~ 9 CSS Hack 写法总结 24th 四, 14 lip2up [code lang="css"]_color: red; /* ie6 */*color: ...
- IOS 开发教程
http://www.raywenderlich.com/category/ios http://www.raywenderlich.com/50310/storyboards-tutorial-in ...