迷宫地图用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);
}
}
}
}
}