您的位置:首页 > 编程语言 > Go语言

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 数据结构