Link

Graph Implementations Reading

Complete the Reading Quiz by noon before lecture.

Before discussing graph implementations, let’s introduce an important problem for motivating graphs. In the previous lecture, we explored the problem of s-t connectivity: given two vertices s and t, determine if s and t are connected. We developed the depth-first search (DFS) algorithm for traversing graphs. In DFS, we visit down the entire lineage of our first neighbor before looking at our second neighbor. In this example, s-t connectivity is a graph problem and DFS is a graph algorithm that solves it.

In the HuskyMaps project, we care not only about whether s and t are connected, but also the shortest path between s and t One way to solve this problem on unweighted graphs is to use breadth-first search (BFS). In BFS, we visit each immediate neighbor before moving on, similar to level-order traversal in a tree. This way, we not only get the shortest path between s and t, but also the shortest paths from s to every other connected (reachable) vertex.

Breadth-first search.

  • Initialize a queue data structure (often called a fringe) with a starting vertex s and mark s.
  • Repeat until the queue is empty:
    • Remove vertex v from the front of the queue.
    • For each unmarked neighbor n of v:
      • Mark n.
      • Set edgeTo[n] = v and distTo[n] = distTo[v] + 1.
      • Add n to end of queue.
edgeTo
A map for identifying the vertex v used to get to n.
distTo
A map for determining the distance from s to every other vertex n.

We set distTo[n] = distTo[v] + 1 because each unmarked neighbor n of v is one edge further away from s! If v is a certain distance from s, then n (a neighbor of v) is one more edge away from s.

Would breadth-first search be a good algorithm for a navigation tool like Google Maps? Assume vertices are intersection and edges are roads connecting intersections.

Not really, because BFS solves shortest paths on an unweighted graph. In reality, some roads are longer than others. BFS keeps track of the distance from s to every other vertex in terms of the number of edges traversed, not the real-world distance.

In the following lecture, we’ll discuss how to resolve the shortest-paths problem on weighted graphs. We can actually use almost all of the ideas from BFS but adapt the fringe to work with edge weights.

In the upcoming lecture, we’ll take a slight detour to discuss graph representation problems, their relationship to graph algorithms, and how to actually implement them in a programming language like Java.


Reading Quiz