Google算法题:贪吃蛇
2017-08-07 14:20
344 查看
题目
题目来源:Link分析
对于Move步骤
(1)检查下一步是否是墙
(2)检查下一步是不是自己,排除下一步是自己的尾巴的情况(特别注意,因为下一步是尾巴的话,头移动过去,尾巴也会跟着移开)
(3)检查是不是食物,是食物的话,将食物位置变成头
(4)如果以上都不是,则表明是空白区,可以走,将下一步插入变成头,将尾巴删除,实现移动
代码
package com.graph; import java.util.*; public class Solution{ public static void main(String[] args) { SnakeEat snake = new SnakeEat(2, 3, new int[][] {{1,2},{0,1}}); snake.move("R"); snake.move("D"); snake.move("R"); snake.move("U"); snake.move("L"); snake.move("U"); } } class SnakeEat{ int n,m; int[][] foods; List<Position> snake = new ArrayList<Position>();//可以用Queue来实现 Set<Position> snakeSet = new HashSet<Position>(); int curFoodIndex; public SnakeEat(int n, int m, int[][] foods){ this.n = n; this.m = m; this.foods = foods; if(foods==null || foods.length==0) curFoodIndex = -1; snake.add(new Position(0,0)); snakeSet.add(new Position(0,0)); } Position head; public void move(String dir){ if(n==0 || (n==1&&m==0) || m==0){ p(-1); return; } //获得下一个位置的坐标 head = snake.get(0); Position next = new Position(); if(dir.equals("U")){ next.x = head.x-1; next.y = head.y; }else if(dir.equals("D")){ next.x = head.x+1; next.y = head.y; }else if(dir.equals("L")){ next.x = head.x; next.y = head.y-1; }else if(dir.equals("R")){ next.x = head.x; next.y = head.y+1; } //检查是不是撞墙 if(next.x<0 || next.x>=n || next.y<0 || next.y>=m){ //isWall p(-1); return; } //检查是不是撞自己 if(snakeSet.contains(next)){ //有一种情况忘记处理,就是当一下步正好是尾巴的位置,因为当头部移动过去,尾巴也移动,所以没有撞到自己 Position tail = snake.get(snake.size()-1); if(next.x==tail.x && next.y==next.y) { }else { //isSelf p(-1); return; } } //检查是不是食物 if(curFoodIndex!=-1){ Position curFood = new Position(foods[curFoodIndex][0], foods[curFoodIndex][1]); //是食物,吃掉 if(next.x==curFood.x && next.y==curFood.y){ if(curFoodIndex==foods.length-1) curFoodIndex=-1; snake.add(0, next);//食物位置变成头 snakeSet.add(next); curFoodIndex++; p(snake.size()-1);//输出当前得分 return; } } //以上检查都通过了,说明是可以走的空白区域 snake.add(0,next);//头部前进 snake.remove(snake.size()-1);//删除尾巴 p(snake.size()-1);//输出当前得分 return; } public void p(int res){ System.out.println(res); } } class Position{ int x,y; public Position(int x, int y){ this.x = x; this.y = y; } public Position(){} }
相关文章推荐
- [转帖]探索Google排名新算法
- Google算法题:二叉树的最大深度
- 基于Google自带算法实时检测人脸并绘制人脸框(网络首发,附完整demo)
- 【每天一道算法题】GOOGLE的服务器
- 贪吃蛇的算法分析(5)
- Google工程师详述Google的搜索结果排列算法[选摘]
- 最权威的Google排名算法解密
- 算法数据挖掘classificationalgorithmgooglevector
- [转]GPS纠偏算法,适用于google,高德体系的地图
- 经典面试题(三)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯
- 最权威的Google排名算法解密
- Google PageRank排名新算法
- 路径分析算法引擎比较 bing map vs google map
- GPS纠偏算法,适用于google,高德体系的地图
- (转自徐倩SEO博客)对于谷歌【Google】最新算法分享
- 字符贪吃蛇游戏设计及算法
- 贪吃蛇(智能蛇的一些算法)
- 经典面试题(一)附答案 算法+数据结构+代码 微软Microsoft、谷歌Google、百度、腾讯
- 2011ACM大赛题目之贪吃蛇算法
- Google I/O 2017上推出的新 GC 算法的原理