Bootstrap

BFS广度优先走迷宫

需要注意的点:

  1. 队列对象实例化:Queue queue = new LinkedList<>();
  2. 取并删除队首元素推荐:queue.poll();
  3. 插入元素到队首推荐:queue.offer(newnode);

运行结果:
在这里插入图片描述


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

public class normal广度走迷宫 {
	int w = 8, h = 8;

	public normal广度走迷宫() {
		
		char map[][] = { { 'O', 'X', 'X', 'X', 'X', 'X', 'X', 'X' }, { 'O', 'O', 'O', 'O', 'O', 'X', 'X', 'X' },
				{ 'X', 'O', 'X', 'X', 'O', 'O', 'O', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'X', 'X', 'O' },
				{ 'X', 'O', 'X', 'X', 'X', 'X', 'X', 'X' }, { 'X', 'O', 'X', 'X', 'O', 'O', 'O', 'X' },
				{ 'X', 'O', 'O', 'O', 'O', 'X', 'O', 'O' }, { 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'O' } };
		BFS(map, 0, 0);

	}


	public void BFS(char map[][], int x, int y) {
		// 优先下右上左
		int H[] = { 1, 0, -1, 0 };
		int W[] = { 0, 1, 0, -1 };
		Queue<bfsNode> queue = new LinkedList<>();
		bfsNode newnode = new bfsNode();
		newnode.x = x;
		newnode.y = y;
		System.out.println(newnode.toString());
		queue.offer(newnode);// 起始节点入队列;
		
		//只要队列不为空
		while (queue.size() > 0) {
			//取队首元素
			bfsNode headnode = queue.poll();
			//如果达到目的,输出结果
			if (headnode.x == h - 1 && headnode.y == w - 1) {
				map[headnode.x][headnode.y] = '*';
				myPrint(map);
				return;
			} else {
				// 把邻居入队列
				for (int k = 0; k < 4; k++) {
					int onex = headnode.x + H[k];
					int oney = headnode.y + W[k];

					if (onex >= 0 && onex < h && oney >= 0 && oney < w && map[onex][oney] == 'O') {
						map[onex][oney] = '*';
						newnode.x = onex;
						newnode.y = oney;
						queue.offer(newnode);
					}
				}

			}

		}

	}

	private void myPrint(char map[][]) {
		System.out.println("+------------------+");
		for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				System.out.print(map[i][j] + " ");
			}
			System.out.println();
		}
		System.out.println();

	}
}

class bfsNode {
	 int x;
	 int y;
	
	public bfsNode() {
		this.x = 0;
		this.y = 0;
	}
}

;