Link

Graph Implementations Study Guide

Graph Traversals Overview. Just as we had both depth-first (pre-order, in-order, and post-order) traversals and a breath-first (level order) traversal for trees, we can generalize these concepts to graphs. Specifically, given a source vertex, we can “visit” vertices in:

DFS Preorder
Order in which DFS is called on each vertex.
DFS Postorder
Order in which we return from DFS calls.
BFS
Order of distance from the source.

Breadth-First Search. Unlike DFS, BFS lends itself more naturally to an iterative solution than a recursive one. When we perform BFS, we visit a source vertex s, then visit every vertex that is one link away from s, then visit very vertex that is two links away from s, and so forth.

Create a fringe of vertices that we think of as the next vertices to be explored. In the case of BFS, this fringe is a queue since we want to visit vertices in the order that we observe them.

fringe.enqueue(s)
mark(s)
while fringe is not empty:
    dequeue(s)
    visit(s)
    for each unmarked neighbor of s:
        mark(s)
        enqueue(s)

In class, we discussed how we could use BFS to solve the shortest paths problem on unweighted graphs: given a source vertex, find the shortest path from that source to every other vertex. When solving shortest paths, we add additional logic to our BFS traversal, where we also set the edgeTo for every vertex at the same time that it is marked and enqueued.

Graph API. Choice of API determines how clients need to think to write codes, since the choice of API can make certain tasks easier or harder. This can also affect runtime and memory.

Graph Implementations. Graph APIs are commonly implemented using adjacency matrices and adjacency lists. With an adjacency matrix, we essentially have a 2-D array with a boolean indicating whether two vertices are adjacent. The more common approach, adjacency lists, maintains an array of lists indexed by vertex number. Each list stores the vertex numbers of all vertices adjacent to the given vertex.

  1. Suppose we run BFS from a an arbitrary start vertex. The edgeTo map represents a BFS tree of the shortest paths (in terms of number of edges) from the start vertex to every other reachable vertex. What, if anything, does the BFS tree tell us about the shortest path between any two vertices, assuming that neither is the start vertex?
  2. Q1a, Q1b from CS 61B 16sp Final (Solution)
  3. Q1a from CS 61B 18sp Final (Solution)