CMPS 144L Spring 2022
Lab #7: Single-source Uniform-cost Shortest Paths

Below left is the distancesFrom() method, which (as discussed in lecture) uses a queue for the purpose of computing the distances from a specified "source" vertex to each of the other vertices in a given directed graph. To its right is a description of a directed graph having vertices numbered 0 through 9.

/* 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 (int y = 0; y != N; y++) {
         if (dist[y] == -1  &&  graph.hasEdge(x,y)) { 
            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;
}
vertexhas edges to
03, 7
12, 9
21, 9
31, 4, 5, 8
42, 8
52, 7, 9
62, 5
72, 6
87
93

Apply the distancesFrom() method to the graph twice, once using vertex 4 as the source and another time using vertex 1 as the source.

Each time, show your work by filling in the missing details in the figures below. The first figure is to describe the sequence of operations that were performed upon the queue, in the manner illustrated both in lecture and on the web page pertaining to queues. The second one is for showing the final contents of the dist[] array.

It is recommended that you copy-and-paste the figures below into a text editor, fill in what's missing, and save the result in a file, which can then be submitted. The jGrasp editor should be suitable for this purpose.

      +----+----+----+----+----+----+----+----+----+----+
      |    |    |    |    |    |    |    |    |    |    |
queue |    |    |    |    |    |    |    |    |    |    |
      |    |    |    |    |    |    |    |    |    |    |
      +----+----+----+----+----+----+----+----+----+----+

enq    ____ ____ ____ ____ ____ ____ ____ ____ ____ ____


deq    ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ 

        0    1    2    3    4    5    6    7    8    9
     +----+----+----+----+----+----+----+----+----+----+
     |    |    |    |    |    |    |    |    |    |    |
dist |    |    |    |    |    |    |    |    |    |    |
     |    |    |    |    |    |    |    |    |    |    |
     +----+----+----+----+----+----+----+----+----+----+