package breadthfirstpaths;
import edu.princeton.cs.algs4.Graph;
import edu.princeton.cs.algs4.Queue;
import edu.princeton.cs.algs4.Stack;
public class BreadthFirstPaths {
private boolean[] marked; //到达该顶点的最短路径是否已知
private int[] edgeTo; //到达该顶点的已知路径上的最后一个顶点
private final int s; //起点
public BreadthFirstPaths(Graph G,int s) {
marked=new boolean[G.V()];
edgeTo=new int[G.V()];;
this.s=s;
bfs(G,s);
}
private void bfs(Graph G,int s) {
Queue<Integer> queue=new Queue<Integer>();
marked[s]=true; //标记起点
queue.enqueue(s); //将它加入队列
while(!queue.isEmpty()) {
int v=queue.dequeue(); //从队列中删去下一顶点
for(int w:G.adj(v))
if(!marked[w]) { //对于每个未被标记的相邻顶点
edgeTo[w]=v;
marked[w]=true; //保存最短路径的最后一条边
queue.enqueue(w); //标记,因为最短路径已知
} //并将它添加到队列中
}
}
public boolean hasPathTo(int v) {
return marked[v];
}
public Iterable<Integer> pathTo(int v){
if(!hasPathTo(v))
return null;
Stack<Integer> path=new Stack<Integer>();
for(int x=v;x!=s;x=edgeTo[x])
path.push(x);
path.push(s);
return path;
}
}
广度优先搜索实现. bfs()方法会标记所有与s连通的顶点, 因此可以调用hasPathTo()来判定一个顶点与s是否连通, 并使用pathTo()得到一条从s到v的路径, 确保没有其他从s到v的路径所含的边比这条路径更少