C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 21 Graphs At a Glance Instructor’s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional Resources Key Terms 21-1 C++ Programming: Program Design Including Data Structures, Fourth Edition 21-2 Lecture Notes Overview Chapter 21 discusses graphs in detail. Students will become familiar with different types of graphs and their representation in the computer. They will also learn about common operations on graphs, graph traversal algorithms, and an algorithm for determining the shortest path through a graph. The chapter concludes by introducing minimal spanning trees and examining Prim’s algorithm for finding a minimal spanning tree. Chapter Objectives Learn about graphs Become familiar with the basic terminology of graph theory Discover how to represent graphs in computer memory Explore graphs as ADTs Examine and implement various graph traversal algorithms Learn how to implement the shortest path algorithm Examine and implement the minimal spanning tree algorithm Teaching Tips Introduction 1. Using Figures 21-1 and 21-2, discuss the Königsberg bridge problem and its role in the history of graph theory. 2. Discuss the many varied applications to which graph theory has been applied. Graph Definitions and Notations 1. Define the set theory terminology presented in this section: Subset Intersection Union Graph Vertices Edges Directed graph (digraph) Undirected graph Origin C++ Programming: Program Design Including Data Structures, Fourth Edition 21-3 Destination Subgraph Adjacent Incident Loop Parallel edges Simple graph Path Connected Simple path Cycle Component Adjacent to Adjacent from Strongly connected 2. Use Examples 21-1 and 21-2 to illustrate directed and undirected graphs. Show the relationship between the pictorial representation of a directed graph and the set of ordered pairs for the graph. 3. Using Figure 21-4 in Example 21-2, discuss relevant terminology such as paths, adjacency, connectedness, and cycles. Teaching Tip Ask your students how the definitions for directed graphs are similar to, or are different from, those for undirected graphs. Teaching Tip Using Figure 21-4, ask your students to identify vertices that have no incoming edges, as well as vertices that have no outgoing edges. Quick Quiz 1 1. Provide a brief description of the Königsberg bridge problem. Who answered the question posed in the problem? What was the answer? Answer: The Königsberg bridge problem is as follows: starting at one land area, is it possible to walk across all the bridges exactly once and return to the starting land area? Euler represented the Königsberg bridge problem as a graph and answered the question in the negative. 2. For a graph G, what does it mean to say that H is a subgraph of G? Answer: A graph H is called a subgraph of graph G if V(H) V(G) and E(H) E(G). In other words, every vertex of H is a vertex of G, and every edge in H is an edge in G. C++ Programming: Program Design Including Data Structures, Fourth Edition 21-4 3. What does it mean to say that a graph G is connected? Strongly connected? Answer: G is called connected if there is a path from any vertex to any other vertex. G is called strongly connected if any two vertices in G are connected. Graph Representation 1. Introduce the two commonly used methods for storing/representing graphs in computer memory: Adjacency matrices Adjacency lists Adjacency Matrix 1. Define an adjacency matrix. 2. Use Example 21-3 to discuss the adjacency matrices for the directed graphs in Figure 21-4. Adjacency Lists 1. Discuss the adjacency list representation for a graph. 2. Use Example 21-4 to give the pictorial view of the adjacency lists for the graphs in Figure 21-4. Teaching Tip Ask your students to compare the adjacency matrix representation with the adjacency list representation. What are the advantages of each? Are there any disadvantages? Have your students compare and contrast storage versus access time. For example, consider the case when the graph has many nodes but few edges and the adjacency matrix is sparsely populated. What does the corresponding adjacency list look like? Operations on Graphs 1. Discuss the most common operations on graphs: Create the graph Clear the graph Determine whether the graph is empty Traverse the graph Print the graph 2. Define the term “immediate successors.” C++ Programming: Program Design Including Data Structures, Fourth Edition 21-5 Graphs as ADTs 1. Discuss the functions in the ADT using the code in this section. Teaching Tip Ask your students to think about how the functions in the ADT would change if the graph was represented by an adjacency matrix. For example, the function clearGraph deallocates storage occupied by each linked list and sets the number of vertices to zero. How would your students clear a graph represented by an adjacency matrix? Graph Traversals 1. Discuss graph traversal and compare it to tree traversal. 2. Introduce two common traversal algorithms (depth first traversal and breadth first traversal). Teaching Tip Ask your students to think about what characteristics of graphs make traversal more difficult than traversing a tree (for example, cycles, loops, and a graph that is not connected). Teaching Tip Ask your students to think about where they would begin traversing a graph. Is the choice of “start node” arbitrary? What if they choose a start node in a directed graph with no outgoing edges? Would their responses change for an undirected graph? Depth First Traversal 1. Discuss the depth first traversal algorithm, comparing it to the preorder traversal algorithm for a binary tree. 2. Illustrate the general algorithm using Figure 21-7. 3. Discuss the C++ implementation of the general algorithm using the code in this section. Breadth First Traversal 1. Discuss the breadth first traversal algorithm, comparing it to traversing a binary tree level-by-level where the nodes at each level are visited from left to right. 2. Illustrate the general algorithm using Figure 21-7. C++ Programming: Program Design Including Data Structures, Fourth Edition 21-6 3. Discuss the C++ implementation of the general algorithm using the code in this section. Ask your students to think about how (or if) the graph traversal algorithms would change if the graph were represented using an adjacency matrix. Teaching Tip Quick Quiz 2 1. True or False: The adjacency matrix representation discussed in this chapter is a twodimensional array that stores any nonnegative integer in each slot in the array. Answer: False 2. List three common operations on graphs. Answer: Create the graph. Clear the graph. Determine if the graph is empty. Traverse the graph. Print the graph. 3. The _________ traversal algorithm for graphs is similar to the preorder traversal of a binary tree. Answer: depth first Shortest Path Algorithm 1. Define the following terms: Weight of the edge Weighted graphs Weight of the path Weight Shortest path Source Shortest path algorithm Greedy algorithm 2. Discuss the notation used to represent weights, and how the weight of a nonexistent edge is denoted. 3. Use the code in this section to discuss the class weightedGraphType. Illustrate how the class graphType is used as a basis for the class weightedGraphType. Shortest Path 1. Discuss the shortest path algorithm. 2. Illustrate how the algorithm works using Example 21-5. C++ Programming: Program Design Including Data Structures, Fourth Edition 21-7 Minimal Spanning Tree 1. Define the terms: (Free) tree Rooted tree Weighted tree Weight of tree t Spanning tree Minimal spanning tree 2. Discuss the spanning tree theorem on page 1337. 3. Using the pseudocode in this section and Figures 21-16 through 21-23, discuss Prim’s algorithm for finding a minimal spanning tree. Quick Quiz 3 1. Who developed the shortest path (or greedy) algorithm? Answer: Dijkstra 2. A graph G must be _________ to determine a spanning tree for G. Answer: connected 3. Define a minimal spanning tree of graph G. Answer: A minimal spanning tree of graph G is a spanning tree with the minimum weight. Class Discussion Topics 1. Ask your students to draw a directed graph that captures the structure for prerequisite computer science courses for the computer science major. 2. Ask your students to extend the graph in Discussion Topic #1 by adding graphs that capture the relationship of other required courses in the BS degree. How many other components would they add (one per department)? Would the components vary by students? By minor? How would your students handle electives? 3. Ask your students to think about what the criteria would be for determining whether or not the minimal spanning tree for graph G is unique (that is, there is only one minimal spanning tree). For example, if the weights are unique, then there is a unique minimal spanning tree. 4. Introduce the Traveling Salesman Problem. Ask your students to think about how they might approach a solution. C++ Programming: Program Design Including Data Structures, Fourth Edition 21-8 Additional Projects 1. Write a program to read in the nodes from a file, and create a graph using an adjacency matrix representation. Using the breadth first traversal algorithm, print out the nodes. 2. Write a program to read the nodes in from a file and create a graph. For a specific node in the graph (which is the one additional value in the input file after the nodes in the graph have been read in), determine if there are any cycles that begin and end with that node. Additional Resources 1. Graphs: http://en.wikipedia.org/wiki/Graph_%28data_structure%29 2. Adjacency matrix: http://en.wikipedia.org/wiki/Adjacency_matrix 3. Minimal spanning trees: www.answers.com/topic/kruskal-s-algorithm http://en.wikipedia.org/wiki/Minimum_spanning_tree http://en.wikipedia.org/wiki/Boruvka%27s_algorithm 4. Traveling salesman problem: http://en.wikipedia.org/wiki/Traveling_salesman Key Terms Adjacency list: a linked list such that each node of the linked list contains a vertex, u, such that A[i] is a reference variable pointing to the first node of the linked list that contains the vertices to which vi is adjacent Adjacency matrix: let G be a graph with n vertices, where n > 0. Let V(G) = {v1, v2, ..., vn}. The adjacency matrix AG of G is a two-dimensional n n matrix, such that the (i, j)th entry of AG is 1 if there is an edge from vi to vj; otherwise, the (i, j)th entry is zero Adjacent: let G be an undirected graph. Let u and v be two vertices in G. Then, u and v are called adjacent if there is an edge from one to the other Adjacent from: in graph G, if there is an edge from u to v, that is, (u, v) is an element of E(G), then we say that v is adjacent from u Adjacent to: in graph G, if there is an edge from u to v, that is, (u, v) is an element of E(G), then we say that u is adjacent to v Breadth first traversal: a traversal algorithm for graphs that is similar to traversing a binary tree level-by-level. In other words, all the nodes at any level, i, are visited before visiting the nodes at level i + 1 Component: a maximal subset of connected vertices in graph G C++ Programming: Program Design Including Data Structures, Fourth Edition 21-9 Connected: vertices u and v are called connected if there is a path from u to v. In other words, a graph G is called connected if there is a path from any vertex to any other vertex Cycle: a simple path in G in which the first and last vertices are the same Depth first traversal: a traversal algorithm for graphs that is similar to the preorder traversal of a binary tree Destination: if (u, v) is an edge in a directed graph, then the vertex v is called the destination Digraph: see directed graph Directed graph: let V(G) denote the set of vertices and E(G) denote the set of edges of a graph G. If the elements of E(G) are ordered pairs, G is called a directed graph or digraph. Also called a digraph Edges: if G is a graph, the edges of G are pairs of elements of V(G), the set of vertices (Free) tree: a simple graph such that if u and v are two vertices in T, then there is a unique path from u to v Graph: a graph G is a pair, G = (V, E), where V is a finite nonempty set of vertices of G, and E is the set of edges such that E V V Greedy algorithm: see shortest path algorithm Immediate successors: for vertex v, the vertices adjacent to v in a directed graph G Incident: let e = (u, v) be an edge in graph G. Edge e is incident on the vertices u and v Intersection: the intersection of sets A and B is the set of all the elements that are in both A and B Loop: an edge incident on a single vertex Minimal spanning tree: a spanning tree with the minimum weight Origin: if (u, v) is an edge in a directed graph, then the vertex u is called the origin of the edge Parallel edges: two edges, e1 and e2, which are associated with the same pair of vertices Path: there is a path from u to v if there is a sequence of vertices u1, u2, . . ., un such that u = u1, un = v, and (ui, ui + 1) is an edge for all i = 1, 2, . . ., n - 1 Rooted tree: a tree in which a particular vertex is designated as a root Shortest path: the path with the smallest weight in weighted graph, G Shortest path algorithm: an algorithm to determine the shortest path through a weighted graph. Also called greedy algorithm Simple graph: a graph with no loops and no parallel edges Simple path: a path in which all the vertices, except possibly the first and last vertices, are distinct Source: the vertex in weighted graph, G, at which a path, P, begins (that is, the first vertex along P) Spanning tree: a subgraph of graph G such that V(T ) = V(G). In other words, all the vertices of G are in T Strongly connected: a graph G is called strongly connected if any two vertices in G are connected Subgraph: a graph H is called a subgraph of graph G if V(H) V(G) and E(H) E(G); that is, every vertex of H is a vertex of G, and every edge in H is an edge in G Subset: a set Y is called a subset of X if every element of Y is also an element of X Undirected graph: let V(G) denote the set of vertices and E(G) denote the set of edges of a graph G. If the elements of E(G) are not ordered pairs, G is called an undirected graph Union: the union of sets A and B is the set of all the elements that are in A or in B C++ Programming: Program Design Including Data Structures, Fourth Edition 21-10 Vertices: the set of nodes in a graph G Weight: see weight of the path Weight of the edge: a nonnegative real number assigned an edge connecting two vertices Weight of the path: the sum of the weights of all the edges on the path, P, in weighted graph, G (also called a weight) Weight of tree T: the sum of the weights of all the edges in T Weighted graph: a graph with weights attached to its edges Weighted tree: a tree, T, for which weights are assigned to the edges in T