BFS求解迷宫问题初探(java版)

BFS,其英文全称是Breadth First Search。 BFS并不使用经验法则算法。从算法的观点,所有因为展开节点而得到的子节点都会被加进一个先进先出的队列中。一般的实验里,其邻居节点尚未被检验过的节点会被放置在一个被称为 open 的容器中(例如队列或是链表),而被检验过的节点则被放置在被称为 closed 的容器中。(详情见百度百科)

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class BFS {

	/**
	 * @param args
	 */
	private static final int M = 4;
	private static final int N = 4;
	int[][] maze;//迷宫布局:1表示障碍物
	int[][] visit;//标记是否已经访问过
	int[][] stepArr = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; //方向:左上右下
	class Node{
		int x, y;
		int step;
		int preX, preY;
		Node(int x, int y, int preX, int preY, int step){
			this.x = x;
			this.y = y;
			this.preX = preX;
			this.preY = preY;
			this.step = step;
		}
	}
	public BFS() {
		// TODO Auto-generated constructor stub
		maze = new int[][]{{0,0, 1, 1},
								{0, 0,0, 1},
								{1, 1,0, 1},
								{0, 0, 0, 0}};
		visit = new int[4][4];
	}
	
	public int bfs(){
		Node node = new Node(0, 0, -1, -1, 0);
		Queue<BFS.Node> queue = new LinkedList<BFS.Node>();
		Stack<BFS.Node> stack = new Stack<BFS.Node>();
		queue.offer(node);
		//visit[0][0] = 1;
		while(!queue.isEmpty()){
			Node head = queue.poll();
			stack.push(head); //用于回溯路径
			visit[head.x][head.y] = 1;
			for(int i = 0; i < 4; i++){
				int x = head.x + stepArr[i][0];
				int y = head.y + stepArr[i][1];
				//exit
				if(x == M -1 && y == N -1 && maze[x][y] == 0 && visit[x][y] == 0){
					//打印路径
					Node top = stack.pop();
					System.out.println("steps:" + (top.step + 1));
					System.out.println("the path:");
					System.out.println((M - 1) + "," + (N - 1));
					System.out.println(top.x + "," + top.y);
					int preX = top.preX;
					int preY = top.preY;
					while(!stack.isEmpty()){
						top = stack.pop();
						if(preX == top.x && preY == top.y){
							System.out.println(preX + "," + preY);
							preX = top.preX;
							preY = top.preY;
						}
						
					}
					return 0;
				}
				//bfs
				if(x >= 0 && x < M && y >= 0 && y < N &&maze[x][y] == 0 && visit[x][y] == 0){
					Node newNode = new Node(x, y, head.x, head.y, head.step + 1);
					queue.offer(newNode);
				}
	
			}
		}
		return -1;
	}	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BFS bfs = new BFS();
		if(bfs.bfs() < 0){
			System.out.println("Fail! Maybe no solution");
		}
		
	}

}


  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值