上机编程题-迷宫问题
来源:互联网 发布:端口能ping吗 编辑:程序博客网 时间:2024/06/06 08:42
用Java实现迷宫求解,基本实现就是DFS搜索,可以实现最短路径。 Point 是一个java类,主要属性石x,y,实现对坐标的抽象。
public final class Demo{private static int dirx[]={0,1,0,-1};private static int diry[]={1,0,-1,0};private int[][] flag;private Point[][] record; //保存路径的栈 private Stack<Point> stack = new Stack<Point>(); public Demo() { } /* 功能:从一个迷宫走出的最短路徑 输入: 一个N*M的数组,int[][] maze迷宫图作为输入,如 {0, 1, 0, 0, 0}, {0, 1, 0, 1, 0}, {0, 0, 0, 0, 0}, {0, 1, 1, 1, 0}, {0, 0, 0, 1, 0}}; 输出:从左上角到右下角的最短路线:(0, 0)(1, 0)(2, 0)(2, 1)(2, 2)(2, 3)(2, 4)(3, 4)(4, 4) */ public Stack<Point> go(int[][] maze) { Point out = new Point(maze.length - 1, maze[0].length - 1); //出口 Point in = new Point(0, 0); //入口//searchQueue<Point> queue= new LinkedList<Point>();queue.offer(in);Point current_point = new Point();Point new_point;flag = new int[maze.length][maze[0].length]; //record 走过没有record = new Point[maze.length][maze[0].length]; //record 前驱节点for(int i = 0 ; i < flag.length ; i++){for(int j = 0 ; j < flag[0].length;j++){flag[i][j] = 0;}}flag[in.getX()][in.getY()] = 1;int x,y;while(!queue.isEmpty()){current_point = queue.peek();queue.poll();if(current_point.getX() == out.getX() && current_point.getY() == out.getY()){break;}for(int i=0;i<4;i++){ //move to 4 directionx = current_point.getX() + dirx[i]; y = current_point.getY() + diry[i];if(x >= in.getX() && x <= out.getX() && y >= in.getY() && y <= out.getY() && maze[x][y] != 1 && flag[x][y] == 0)// judge whether is accessible or back or out of board //防止坐标溢出,同时判断是否碰到墙壁或者走回原路{new_point = new Point(x,y);queue.add(new_point);flag[new_point.getX()][new_point.getY()] = 1;//recordrecord[new_point.getX()][new_point.getY()] = current_point;}}}//pathif(flag[current_point.getX()][current_point.getY()] != 0){Stack<Point> path = new Stack<Point>();path.push(out);int i = record[out.getX()][out.getY()].getX();int j = record[out.getX()][out.getY()].getY();while(i != in.getX() || j != in.getY()){path.push(new Point(i,j));int m = record[i][j].getX();int n = record[i][j].getY();i=m;j=n;}path.push(new Point(0,0));Collections.reverse(path);return path;}else{return null;} } }
0 0
- 上机编程题-迷宫问题
- 算法编程(JAVA)--迷宫问题
- 编程练习:走迷宫问题
- 数据结构上机实验任务——迷宫求解问题
- 小编程题--解决一维迷宫问题
- 青蛙走迷宫问题--滴滴笔试编程题
- 上机编程题-约瑟夫问题(升级版)
- 上机编程题
- 编程练习:走迷宫问题后续
- 上机笔试编程训练 背包问题
- [编程题] 地下迷宫 滴滴编程题
- 迷宫编程
- 刷刷笔试题~~[迷宫问题!!]
- bfs简单题 迷宫问题
- 第十二周上机实践—项目5—迷宫问题之图深度优先遍历解法
- 第12周上机实践项目5 - 迷宫问题之图深度优先遍历解法
- Java上机题,背包问题
- 迷宫问题
- 基本数据类型 进制转换
- android application
- 深入解析C语言声明
- UI_Delegate
- 通过ApplicationContextAware加载Spring上下文环境
- 上机编程题-迷宫问题
- 文章标题
- Redis服务器剖析
- Android高仿微信图片多选功能
- Android中View属性大全
- 杭电(hdu)1702 ACboy needs your help again!
- Oracle如何&操作进行二进制的比对
- jQuery 效果 - toggle() 方法
- C#遍历查询文本框是否为空,判断文本框是否为数字,一键清空文本框内容