Google算法题:贪吃蛇
来源:互联网 发布:java葵花宝典2017 编辑:程序博客网 时间:2024/06/05 20:29
题目
题目来源: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){//isWallp(-1);return;}//检查是不是撞自己if(snakeSet.contains(next)){//有一种情况忘记处理,就是当一下步正好是尾巴的位置,因为当头部移动过去,尾巴也移动,所以没有撞到自己Position tail = snake.get(snake.size()-1);if(next.x==tail.x && next.y==next.y) {}else {//isSelfp(-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(){}}
阅读全文
0 0
- Google算法题:贪吃蛇
- 贪吃蛇算法分析
- cocosx2d_x 贪吃蛇算法
- 贪吃蛇游戏算法
- 【游戏算法之贪吃蛇】我想的贪吃蛇算法
- 贪吃蛇的算法分析
- C++ 贪吃蛇基本算法
- 贪吃蛇设计与算法
- 智能贪吃蛇设计算法
- 贪吃蛇的算法分析(1)
- 贪吃蛇的算法分析(2)
- 贪吃蛇的算法分析(3)
- 贪吃蛇的算法分析(4)
- 贪吃蛇的算法分析(5)
- 贪吃蛇的算法分析(1)
- 贪吃蛇的算法分析(2)
- 贪吃蛇的算法分析(3)
- 贪吃蛇的算法分析(4)
- axis
- MYSQL存储过程循环遍历插入数据
- [LeetCode] 58. Length of Last Word
- Npm简介
- 读《人类简史》有感
- Google算法题:贪吃蛇
- 运动控制有哪些方法
- 解决 命名空间中不存在类型或命名空间名称“App_Code”(是否缺少程序集引用?)的问题
- maven在父级项目文件夹下创建子项目
- 1.初步启动树莓派
- 前端好用的插件
- Caused by: java.lang.ClassNotFoundException,还有关于包冲突一些问题
- 数据结构实验之链表三:链表的逆置
- js学习笔记