package graphs.digraphs; import java.util.Queue; import java.util.LinkedList; import java.util.Stack; /************************************************************************* * Run breadth first search on a digraph. */ public class DiGraphBFSPath { private static final int INFINITY = Integer.MAX_VALUE; private boolean[] visited; // visited[v] = is there an s-v path? private int[] distTo; // distTo[v] = length of shortest s-v path private int[] edgeTo; // edgeTo[v] = last edge on shortest s-v path private final int s; // the source public DiGraphBFSPath(DiGraph G, int s) { this.s = s; visited = new boolean[G.numberOfVerteces()]; distTo = new int[G.numberOfVerteces()]; edgeTo = new int[G.numberOfVerteces()]; for (int v = 0; v < G.numberOfVerteces(); v++) distTo[v] = INFINITY; distTo[s] = 0; visited[s] = true; bfs(G, s); } private void bfs(DiGraph G, int s) { Queue<Integer> q = new LinkedList<Integer>(); q.add(s); while (!q.isEmpty()) { int v = q.poll(); for (int w : G.adjacents(v)) { if (!visited[w]) { q.add(w); edgeTo[w] = v; distTo[w] = distTo[v] + 1; visited[w] = true; } } } } // length of shortest path from s to v public int distanceTo(int v) { return distTo[v]; } // is there a directed path from s to v? public boolean hasPathTo(int v) { return visited[v]; } // return shortest path from s to v; null if no such path public Iterable<Integer> pathTo(int v) { if (!hasPathTo(v)) return null; Stack<Integer> stack = new Stack<Integer>(); for (int x = v; x != s; x = edgeTo[x]) stack.push(x); stack.push(s); return stack; } }