Establishment of queue
static Queue r = new LinkedList(); //创建队列
(Learning video sharing: java course)
Basic method of queue
r.offer(); Enter the end of the queue
r.poll(); Exit the first part of the queue
r.peek(); Contents of the first part of the queue
Code implementation :
Global variable setting
package Two; import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; public class BFS { static int a[][] = new int [100][100]; //输入迷宫 static int v[][] = new int [100][100]; //走过的标记为1 static int startx,starty; //输入起点位置 static int p,q; //输入要到达的坐标位置 static int dx[] = {0,1,0,-1}; //方向数组 static int dy[] = {1,0,-1,0}; static Queue<point> r = new LinkedList<point>(); //创建队列 static class point{ //建立类坐标属性 int x; int y; int step; }
Input the maze and starting position, target position
public static void main(String[] args) { Scanner in = new Scanner(System.in); int m = in.nextInt(); int n = in .nextInt(); for(int i=1;i<=m;i++) //输入迷宫 for(int j=1;j<=n;j++) a[i][j] = in.nextInt(); startx = in.nextInt(); starty = in.nextInt(); //输入目标和起始位置 p = in.nextInt(); q = in.nextInt();
BFS algorithm start
1. Set the team leader
//BFS point start = new point(); //定义一个初始类作为队首 start.x = startx; start.y = starty; start.step = 0; r.offer(start); v[startx][starty]=1;
2. Enter the loop body
while(!r.isEmpty()) { //当队列为空时跳出循环 int x = r.peek().x; //把队首的属性赋值 int y = r.peek().y; int step = r.peek().step; if(x==p && y==q) { //到达目的地,退出循环 System.out.println(step); break; } for(int i=0;i<4;i++) { //广度遍历,右下左上分别入队 int tx= x+dx[i]; int ty= y+dy[i]; if(a[tx][ty] == 1 && v[tx][ty]==0) { //判断是否可以入队 //入队 point temp = new point(); //建立一个临时类 temp.x = tx; temp.y = ty; temp.step = r.peek().step +1; r.offer(temp); //入队 v[tx][ty]=1; //标记为1 } } r.poll(); //拓展完了需要队首出队 } } }
Related recommendations:Getting started with java
The above is the detailed content of Use java algorithm BFS to find the shortest path to the maze exit. For more information, please follow other related articles on the PHP Chinese website!