/* Given a directed graph and the ID v of a vertex in that graph
** (the so-called "source" vertex), returns an array indicating,
** for each vertex w in the graph, the distance from v to w.
*/
public static int[] distancesFrom( DiGraph graph, int v ) {
final int N = graph.numVertices();
int[] dist = new int[N];
for (int i = 0; i != N; i++) { dist[i] = -1; }
dist[v] = 0;
Queue<Integer> q = new QueueViaX<Integer>();
q.enqueue(v); // insert source vertex onto queue
while (!q.isEmpty()) {
int x = q.dequeue(); // grab a vertex x off the queue
// now explore from vertex x
for each y such that graph.hasEdge(x,y) {
if (dist[y] == -1) {
q.enqueue(y); // y is newly discovered!
dist[y] = dist[x] + 1; // distance to y from v
} // is one more than from
} // v to x
}
return dist;
}
|