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 queue = new LinkedList();
		Stack stack = new Stack();
		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");
		}
		
	}

}


你可能感兴趣的:(算法)