Exercises on Graph Traversal and Unweighted Distance
1Problem 1: Paths, distance, and connected components
Let the undirected graph be defined by
- List every path of length 2 from to .
- Find and .
- Find all connected components.
1.1Solution
The length-2 paths are and . Therefore . No path joins to , so . The connected components are and .
2Problem 2: DFS and BFS order
Use the graph from Problem 1 and examine every adjacency list in alphabetical order. Start at and mark a vertex visited when it is added to the candidates.
- Determine the first-visit order of recursive DFS.
- Determine the first-visit order of BFS.
- Find the traversal levels recorded by BFS and verify that they equal the distances from to every reachable vertex.
2.1Solution
DFS visits . It proceeds from to , from to , and then from to the unvisited vertex .
BFS visits . The recorded distances are
These levels equal the lengths of the shortest paths found in Problem 1. Vertices are unreachable from .
3Problem 3: When to mark a vertex visited
Run BFS on the triangle graph
Explain what duplication may occur if a vertex is not marked visited until it is removed from the queue. Then explain why marking it when it is added prevents the duplication.
3.1Solution
Processing adds to the queue. When is removed, may still be unvisited, so edge can add again, leaving two copies of in the queue.
If a vertex is marked at insertion, then immediately after its first insertion. A later examination through another edge fails the condition , so every vertex is added to the candidates at most once.
4Problem 4: Representation, complexity, and method selection
Answer the following questions for an undirected graph with and .
- Give the number of edge entries stored in adjacency lists and their space complexity.
- Give the space complexity and edge-query time of an adjacency matrix, and choose a representation for a sparse graph.
- Explain the running time of DFS and BFS with adjacency lists.
- State whether DFS or BFS applies to unweighted shortest distance, reachability, and shortest distance with unequal edge weights.
4.1Solution
Each undirected edge appears once in the list of each endpoint, so there are edge entries and the lists, including the vertex headers, use space. An adjacency matrix uses space but answers an edge-existence query in time. Adjacency lists are preferable for a sparse graph, where is much smaller than .
With adjacency lists, each vertex is processed at most once and each undirected edge is examined at most once from each endpoint. Thus DFS and BFS run in time. Use BFS for unweighted shortest distance. Either DFS or BFS determines reachability. Neither ordinary DFS nor ordinary BFS guarantees shortest distance when edge weights differ; for nonnegative weights, use a method such as Dijkstra's algorithm.