bfs_迷宫求最短路径
2017-03-31 21:03
477 查看
宽度优先搜索按照距离开始状态由近及远的顺序进行搜索,可以很容易用来求解最短路径或者最少操作等问题。
将已经访问过的状态用标记管理起来,便可以很好地做到由近及远的搜索。
将已经访问过的状态用标记管理起来,便可以很好地做到由近及远的搜索。
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class Main { static int n,m; static char[][] maze; static int [][] dis; final static int INF = 100000000; static int gx,gy; static int sx,sy; static int dx[] = new int[]{1,0,-1,0}; static int dy[] = new int[]{0,1,0,-1}; static int bfs(){ Queue<Pair> queue = new LinkedList(); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++) dis[i][j] = INF; } queue.add(new Pair(sx,sy)); dis[sx][sy] = 0; while(!queue.isEmpty()){ Pair p = queue.remove(); System.out.println(p.x + " "+ p.y); if(p.x == gx && p.y == gy) break; for(int i = 0; i < 4; i++){ int nx = p.x + dx[i]; int ny = p.y + dy[i]; if(0 <= nx && nx < n && 0 <= ny && ny < m && maze[nx][ny] != '#' && dis[nx][ny] == INF){ queue.add(new Pair(nx,ny)); dis[nx][ny] = dis[p.x][p.y] + 1; } } } return dis[gx][gy]; } public static void main(String[] args) { Scanner in = new Scanner(System.in); n = in.nextInt(); m = in.nextInt(); maze = new char [m]; dis = new int [m]; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ maze[i][j] = in.next().charAt(0); if(maze[i][j] == 'S'){ sx = i; sy = j; } if(maze[i][j] == 'G'){ gx = i; gy = j; } } } System.out.println(bfs()); } } class Pair{ public Pair(int x, int y){ this.x = x; this.y = y; } int x; int y; }
相关文章推荐
- 迷宫的最短路径(bfs)
- 仙岛求药(BFS迷宫寻找最短路径)
- BFS和DFS的差别,BFS实现迷宫最短路径
- 迷宫最短路径dfs和bfs代码分析
- POJ 3322 Bloxorz I(BFS:求迷宫最短路径)
- 迷宫最短路径求解(BFS)
- hdu1728逃离迷宫 (利用最短路径思想+优先队列(BFS))
- 迷宫的最短路径(BFS的简单应用)
- cdoj1088-王之迷宫 (三维迷宫最短路径)【BFS】
- 迷宫的最短路径(bfs)
- zoj1649-Rescue (迷宫最短路径)【bfs 优先队列】
- BFS 迷宫的最短路径问题
- BFS求迷宫的最短路径
- 迷宫的最短路径(深度bfs)
- bfs走迷宫记录最短路径(求大神指…
- 回溯法-bfs--迷宫问题的最短路径
- bfs 迷宫输出最短路径
- 迷宫最短路径长度bfs
- POJ 3984---迷宫问题(BFS,迷宫最短路径且输出路径)
- poj 3984迷宫问题(bfs求最短路径 类似并查集保存上个节点 保存最短路径)