无向图的广度优先遍历通过队列来实现,广度优先队列可以用来实现查找最短路径,也就是距离两个点之间边最少的路径,先让顶点进队列,然后出队列,把和顶点相连通的点入队列,借助队列的先入先出特性来实现广度优先遍历。寻找路径的API如下:(Graph 请看前面无向图的邻接表实现)
BreadthFirstPaths(Graph G, int s) 在G中找出所有起点为s的路径
boolean hasPathTo(int v) 是否存在从s到v的一天路径
Iterable pathTo(int v) s到v的路径,如果不存在则返回null
public class BreadthFirstParhs{
private int[] edgeTo; //从起点到一个顶点的当前路径的最后一个顶点
private boolean[] marked; //判断一个顶点是否已经遍历过
private int s; //起点
public BreadthFirstParhs(Graph G,int s){
marked = new boolean[G.V()];
this. s = s;
edgeTo = new int[G.V()];
bfs(G,s);
}
private void bfs(Graph G,int v){
Queue<Integer> queue = new Queue<Integer>();
marked[v] = true; //标记起点
queue.enqueue(v); //将其加入队列
while(!queue.isEmpty()){
int w = queue.dequeue(); //从队列中删除下一节点
edgeTo[w]