广度优先搜索迷宫的最短路径走法!

引用自我的上一篇博客:用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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值