引用自我的上一篇博客:用DFS实现的走迷宫,这里用BFS再走一遍!
感觉最近快迷失在迷宫里面了!可怕。。。
不说了上代码,有问题希望大神们指出来!虚心接受!
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/*
* 结合BFS实现的 迷宫走法
*
* */
public class bfsmigong {
static int p;// 终点x坐标
static int q;// 终点y坐标
static int startx;// 起点x坐标
static int starty;// 起点y左边
static int[][] book;// 标记数组,用来记录是否已经访问过该坐标
static int n;
static int m;
static int[][] a;
static int[][] d=new int[51][51];
static int next[][] = new int[][] { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }, };
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
a = new int[51][51];
book = new int[51][51];
for (int i = 1; i <= n; i++) {// 读入数组,舍弃0行0列 角标,从第一行第一列角标开始 读入数组中
for (int j = 1; j <= m; j++) {
a[i][j] = sc.nextInt();
}
}
// sop(a, m, n);
startx = sc.nextInt();
starty = sc.nextInt();
p = sc.nextInt();
q = sc.nextInt();
note temp = new note(startx, starty);
Queue<note> queue = new LinkedList<note>();
queue.offer(temp);
book[startx][starty] = 1;// 初始化起点为1,表示已经访问过了。
int flag = 0;
int sum = 0;
int tx, ty;
while (!queue.isEmpty()) {
note local = queue.remove();
for (int k = 0; k <= 3; k++) {
tx = local.x + next[k][0];
ty = local.y + next[k][1];
note nbr = new note(tx, ty);
if (nbr.x < 1 || nbr.y < 1 || nbr.x > n || nbr.y > m) {
continue;
}
if (a[nbr.x][nbr.y] == 0 && book[nbr.x][nbr.y] == 0) {
book[nbr.x][nbr.y] = 1;
queue.offer(nbr);
d[tx][ty]=d[local.x][local.y]+1;
}
if (tx == p && ty == q) {
flag = 1;
break;
}
}
if (flag == 1) {
break;
}
}
System.out.println(d[p][q]);
}
}
class note {
int x;
int y;
int s;
note(int x, int y) {
this.x = x;
this.y = y;
}
}
/*
*
*
*
*/
测试数据:
5 4
0 0 1 0
0 0 1 0
0 0 0 0
0 1 0 0
0 0 0 1
1 1 4 3
输出:7