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-lib——JsonConfig详细使用说明
在使用json-lib包中JSONObject.fromObject(bean,cfg)时,可能出现以下几种情况: 1.(防止自包含)转换的对象包含自身对象,或者对象A下面挂了对象B,对象B下面又挂了 ...
- Unity4.0的使用
最近公司用到了Unity,自己就研究了一下. 新建一个ASP.NET MVC基本项目,在NuGet上引入Unity4.0.1最新版. 因为我使用的项目为ASP.NET MVC,所以又添加一个Unity ...
- HDU1003 简单DP
Max Sum Problem Description Given a sequence a[1],a[2],a[3]......a[n], your job is to calculate the ...
- 有限状态机(FSM)
在游戏开发中,AI是个永恒不变的话题,如果你要的AI只是很简单的一个逻辑 那么有限状态机是一个很好的解决方案,尽管在实际开发中,AI的设计并不是一个简单的逻辑, 如果用有限状态机,维护起来会非常麻烦, ...
- MSSQL 跨服器调用存储过程
A库 CREATE PROCEDURE [dbo].[A_P_Test] AS BEGIN SELECT * FROM dbo.A_LoadData END B库 在B中调用A库存储过程 注:是同一 ...
- 【Alpha】Daily Scrum Meeting第七次
一.本次Daily Scrum Meeting主要内容 各队员的任务完成情况 文件选择器布局只是暂时使用,后期会改方式,放在后面解决. 接下去都要做什么 二.项目进展 学号尾数 今日已完成任务 接下去 ...
- ListView使用item显示不同布局
/** * 自定义城市列表适配器 */ private class MyCityListAdapter extends BaseAdapter { final int VIEW_TYPE = 2; f ...
- 2016huasacm暑假集训训练四 递推_C
题目链接:http://acm.hust.edu.cn/vjudge/contest/125308#problem/C 题意:给你一个高为n ,宽为m列的网格,计算出这个网格中有多少个矩形 这个题只 ...
- juqery 拖拽元素
转自 http://www.cnblogs.com/holbrook/archive/2012/03/13/2394111.html 因为怕博主删除博客,所以复制过来! JQuery UI是JQue ...
- ubuntu-vnc
Centos 中文gnome: 全新以最小化包安装了64位的CentOS6.3系统,作为本地的Web服务器使用,现记录全过程: 1.先安装X Window yum groupinstall " ...