Graph Traversal



Labeled Graph ADT

public class Graph {
  private boolean [] [] edges;
  private Object [] labels;

public Graph (int n) { edges = new boolean [n] [n]; labels = new Object [n]; // null }



Graph Traversal



Depth-first traversal



Breadth-first traversal



Graphs with weighted Edges



In-class exercise



Dijkstra's Shortest Path Algorithm



Dijkstra's Shortest Path Algorithm



Dijkstra's Shortest Path Algorithm Main Loop

  1. search the distances array to find the closest vertex NOT yet in the allowed set (any one if there is several with the same distance). Call this vertex next
  2. add next to the allowed set A
  3. revise the distances array for all the neighbors of next, since this new vertex may now appear on permitted paths



Why does this work?

Invariants:
  1. we know the distance for all vertices in A
  2. the distance for all vertices in A is less than for any vertices not in A
  3. we know the distance d for all neighbors of the vertices in A, including the nearest vertex NOT in A
  4. when we add next to A:



Keeping Track of the Path



Find the closest vertex not in A



Add this vertex to A



Update the distance of the neighbors of next