BFS_2:迷宫最短路径
输入样例:
5 5
1 0 1 1 1
0 0 1 1 0
1 0 1 1 1
0 0 1 1 1
0 0 0 1 1
5
(5,3)->(5,2)->(4,2)->(3,2)->(2,2)
问题分析:
该题为经典题,典型的BFS搜索最短路径,比较要注意的是pre成员属性,用于记录当前节点的前一个节点,从而寻找最短的路径。
二、使用步骤
import java.util.*;
class Node{
public int x;
public int y;
public int dis;
public Node pre;//用来记录路径
public Node(int x, int y) {
this.x = x;
this.y = y;
}
public Node(int x, int y, int dis) {
this.x = x;
this.y = y;
this.dis = dis;
}
}
public class BFS_2 {
static int N = 40;
static int n,m;
static int[][] mp = new int[N][N];
static int[][] vis = new int[N][N];
static int[] xx = {0 ,0 , -1 , 1};
static int[] yy = {-1 ,1 ,0 , 0 };
static Node end;
static Node start;
static List<Node> path = new ArrayList<>();
static Queue<Node> queue = new LinkedList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
m = scanner.nextInt();
start = new Node(1,2,0) ;
end = new Node(5,3) ;
for (int i = 1; i <= n ; i++) {
for (int j = 1; j <= m ; j++) {
mp[i][j] = scanner.nextInt();
}
}
bfs(start);
}
private static void bfs(Node node) {
//将队首元素压入队列
StringBuilder s = new StringBuilder();
queue.offer(node);
vis[node.x][node.y] = 1;
//开始进行搜索
while (!queue.isEmpty()){
Node cur = queue.peek();
//如果当前的点是终点的话,则退出
if(cur.x==end.x&&cur.y== end.y) {
System.out.println(cur.dis);
System.out.print("("+cur.x+","+cur.y+")->");
for (int j = path.size()-1; j >= 0 ; j--) {
if(path.get(j) == cur.pre){
s.append("(").append(path.get(j).x).append(",").append(path.get(j).y).append(")->");
cur = path.get(j);
}
}
s.delete(s.length()-2,s.length());//处理尾巴
System.out.println(s);
}
for (int i = 0; i < 4; i++) {
int dx = cur.x + xx[i];
int dy = cur.y + yy[i];
//判断该点是否可以走
if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&mp[dx][dy]==0&&vis[dx][dy]==0){
Node temp = new Node(dx,dy);
vis[temp.x][temp.y]= 1 ;
temp.dis = cur.dis + 1;
temp.pre = cur;
path.add(temp);
//入队
queue.offer(temp);
}
}
//当队首元素的所有方向都找完之后,出队列
queue.poll();
}
}
}