BFS算法之迷宫最短路线

迷宫地图用0和1表示,1代表通路,0表示不通。

 

代码

 

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class bfs {

	/**
	 * bfs
	 */

	public static void main(String[] args) {

		class Node {
			int x;
			int y;
			int prex;
			int prey;

			Node(int x, int y, int prex, int prey) {
				this.x = x;
				this.y = y;
				this.prex = prex;
				this.prey = prey;
			}
		}

		int maze[][] = new int[][] { { 1, 0, 0, 1 }, { 1, 1, 0, 1 },{ 0, 1, 1, 0 }, { 0, 0, 1, 1 } };	//迷宫地图
		int mark[][] = new int[4][4];
		int nexts[][] = new int[][] { { 1, 0 }, { 0, 1 }, { -1, 0 }, { 0, -1 } };	//四个搜索方向

		Queue<Node> queue = new LinkedList<Node>(); // 初始化队列
		Stack<Node> stack = new Stack<Node>();
		queue.offer(new Node(0, 0, -1, -1));	//起点为(0,0)
		mark[0][0] = 1;
		while (!queue.isEmpty()) {

			Node local = queue.poll();
			stack.push(local);
			for (int i = 0; i < nexts.length; i++) {
				int x = local.x + nexts[i][0];
				int y = local.y + nexts[i][1];
				Node next = new Node(x, y, local.x, local.y);

				if (x == 3 && y == 3 && maze[x][y] == 1 && mark[x][y] == 0) {	//输出路线
                                        System.out.println("3,3");
					while (!stack.isEmpty()) {
						Node n = stack.pop();
						System.out.println(n.x + "," + n.y);
					}
					break;
				}

				if (x < 4 && y < 4 && y >= 0 && x >= 0 && mark[x][y] == 0
						&& maze[x][y] == 1) {	//判断是否满足条件并继续向下搜索
					mark[x][y] = 1;
					queue.offer(next);
				}

			}

		}

	}

}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值