BFS 经典题目详解



【POJ】3984 迷宫问题(入门)

原题链接:http://poj.org/problem?id=3984

  • 思路: 求最短路径一般就是广度优先搜索,定义一个结构体,不仅有x,y坐标,还要有pre,表示前一个元素下标,即保存路径。从左上角(0, 0)位置开始搜索,分别向上下左右搜索,已走过的点标记为1,未走过且可以走的点压入队列,最后当搜索到终点的时候,再把队列里的路径从头到尾一个个递归输出。

Code:

import java.util.Scanner;
class node{
	int x,y,pre;
	public node() {}
	public node(int x,int y,int pre) {
		this.x=x;
		this.y=y;
		this.pre=pre;
	}
}
public class Main {
	static int front=0,rear=1;
	static int[][] dir = {{1,0},{-1,0},{0,1},{0,-1}};
	static int[][] maps = new int[10][10];
	static node[] q = new node[100];
	static void print(int index) {
		if(q[index].pre!=-1) {
			print(q[index].pre);
			System.out.println("("+q[index].x+", "+q[index].y+")");
		}
	}
	static void bfs(int x,int y) {
		q[front]= new node(x,y,-1);
		while(front<rear) {
			for(int i=0;i<4;i++) {
				for(int j=0;j<4;j++) {
					int xx=q[front].x+dir[i][0];
					int yy=q[front].y+dir[i][1];
					if(xx<0||xx>4||yy<0||yy>4||maps[xx][yy]!=0)
						continue;
					maps[xx][yy]=1;
					q[rear] = new node(xx,yy,front);
					if(xx==4&&yy==4)	print(rear);
					rear++;
				}
			}
			front++;
		}
	}
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		for(int i=0;i<5;i++)
			for(int j=0;j<5;j++)
				maps[i][j]=cin.nextInt();
		for(int i=0;i<100;i++)	//结构体要全部初始化,不然搜索时会报空指针异常
			q[i]=new node();
		System.out.println("(0, 0)");
		bfs(0,0);
	}
}


发布了123 篇原创文章 · 获赞 57 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_44668898/article/details/104163073
BFS