花了一下午终于把bfs搞懂了,手写一道例题
package BFS;
import java.util.LinkedList;
import java.util.Scanner;
public class 迷宫 {
static int health,with;
static char map[][];
static Boolean mapCheck[][];
/**
* 空间向量
*/
static int x[] = {0,0,1,-1};
static int y[] = {1,-1,0,0};
/**
* BFS广度优先搜索
* @param
*/
static int BFS(Pair start,Pair end) {
//定义队列
LinkedList q = new LinkedList<>();
//将起点入队
q.offer(start);
while (!q.isEmpty())
{
Pair top = q.peek(); //取出队头并且d出
q.poll();
if (top.x == end.x && top.y == end.y) return top.step; //是否到达终点
for (int i=0;ihealth || x<1 || y>with || y<1) return false; //超出坐标地图
if (map[x][y] == '*') return false; //障碍
if (mapCheck[x][y] == null) return true; //没有入队
else return false;
}
public static void main(String[] args) {
/**
* 迷宫地图长度是否入队初始化
*/
Scanner sc = new Scanner(System.in);
health = sc.nextInt();
with = sc.nextInt();
map = new char[health+1][with+1];
mapCheck = new Boolean[health+1][with+1];
for (int i=1;i<=health;i++)
{
String s = sc.next();
for(int j = 1;j<=with;j++)
map[i][j] = s.charAt(j-1);
}
/**
* 起点和终点坐标
*/
Pair start = new Pair(sc.nextInt()+1,sc.nextInt()+1);
Pair end = new Pair(sc.nextInt()+1,sc.nextInt()+1);
start.step = 0;
System.out.println(BFS(start,end));
}
}
/**
* 存储每个节点的状态
*/
class Pair{
int x,y,step;
public Pair(int x, int y){this.x = x; this.y = y;}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)