迷宫的路径问题
来源:互联网 发布:程序员需要算法吗 编辑:程序博客网 时间:2024/04/27 21:40
在程序设计中,关于迷宫的问题,有书中提到迷宫的最短路径问题,并给出了相关C代码,思考良久,利用宽度优先算法怎么可以得到最短路径,百思不得解,将C代码改写java代码后经测试发现,的确不能得到最短路径,充其量也只能得到其中的一条路径。现将代码献上。
public class ShortestPath { private static char[][] path = new char[][]{ {'#','S','#','#', '#', '#', '#', '#', '.','#'}, {'.','.','.','.', '.', '.', '#', '.', '.','#'}, {'.','#','.','#', '#', '.', '#', '#', '.','#'}, {'.','#','.','.', '.', '.', '.', '.', '.','.'}, {'#','#','.','#', '#', '.', '#', '#', '#','#'}, {'.','.','.','.', '#', '.', '.', '.', '.','#'}, {'.','#','.','#', '#', '#', '#', '#', '.','#'}, {'.','.','.','.', '#', '.', '.', '.', '.','.'}, {'.','#','.','#', '#', '.', '#', '#', '#','.'}, {'.','.','.','.', '.', '.', '.', '.', 'G','#'} }; private static int sx, sy; private static int gx = 9, gy = 8; static int dx[] = {1,0,-1,0}; static int dy[] = {0,1,0,-1}; private static int d[][] = new int[path.length][path[0].length]; public static void main(String argsp[]) { int res = bfs(); for(int i = 0 ; i< d.length ; i++) { System.out.println(Arrays.toString(d[i])); } System.out.println(res); } private static int bfs() { sx = 0; sy = 1; for(int i= 0; i < path.length; i++) { for(int j = 0; j < path[0].length; j++) { d[i][j] = 0; } } d[sx][sy] = 1; Deque<Point> queue = new ArrayDeque<>(); queue.push(new Point(sx,sy)); while(!queue.isEmpty()) { Point p = queue.pop(); if(p.getX() == gx && p.getY() == gy) { break; } for(int i = 0; i<4; i++) { int nx = p.getX() + dx[i], ny = p.getY() + dy[i]; if(0 <= nx && nx < path.length && 0 <= ny && ny < path[0].length && path[nx][ny] != '#' && d[nx][ny] == 0) { queue.push(new Point(nx, ny)); d[nx][ny] = d[p.getX()][p.getY()] + 1; } } } return d[gx][gy]; } static class Point{ private int x; private int y; public Point(int x, int y) { super(); this.x = x; this.y = y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public String toString() { return "Point [x=" + x + ", y=" + y + "]"; } }}
阅读全文
0 0
- 迷宫的路径问题
- 迷宫问题(如何将走去迷宫的路径输出?)
- BFS 迷宫的最短路径问题
- 迷宫问题的最短路径
- 迷宫的最优路径
- 迷宫问题(唯一路径)
- 迷宫问题bfs+打印路径
- 栈-迷宫求解路径问题
- 迷宫最短路径问题
- 迷宫问题(输出路径)
- 迷宫问题并求最短路径
- bfs迷宫问题--打印路径
- 迷宫问题求最小路径
- 迷宫问题,最短路径
- 迷宫路径搜索问题(栈的链表实现)
- POJ 2984 迷宫问题(搜索 路径的还原)
- 复杂迷宫问题的递归实现以及最短路径
- POJ 3984 迷宫问题(记录路径的搜索)
- 进程和程序的区别?
- 八大算法思想(一)------------------枚举算法
- 如何学好编程?学习经验汇总
- C/S架构和B/S架构的区别
- samba
- 迷宫的路径问题
- 关于C单链表的面试题(基础篇)
- 递归版的插入排序和选择排序
- lua青葱之路---冒号使用
- 数组方法(学习笔记2017-6-9)
- 推荐算法
- 深圳乐易网络有限公司机试题String to Integer (atoi)
- 后端优化策略
- 数据结构——顺序表(C语言实现)