Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright  1997 Oxford University Press All Rights Reserved

Similar presentations


Presentation on theme: "Copyright  1997 Oxford University Press All Rights Reserved"— Presentation transcript:

1 Copyright  1997 Oxford University Press All Rights Reserved
Figures from Chapter 12 of Data Structures via C++ Objects by Evolution A. Michael Berman Copyright  1997 Oxford University Press All Rights Reserved

2 Copyright  1997 Oxford University Press All Rights Reserved
5/14/2019 Chapter 12 Graphs Overview Graphs provide a rich and powerful way to model relations. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

3 Copyright  1997 Oxford University Press All Rights Reserved
5/14/2019 Chapter Objectives 1. To review basic graph vocabulary and concepts. 2. To develop classes that model various kinds of graphs. 3. To learn some useful algorithms for manipulating graphs. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

4 Copyright  1997 Oxford University Press All Rights Reserved
Table 12-1 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

5 Figure 12-1: Course Prerequisites in Graphical Form
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

6 Figure 12-2: An Example Graph
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

7 Figure 12-3: An Example Digraph
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

8 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 12-1 For an undirected graph of n vertices, what is the largest number of edges it can have? For a directed graph? (Assume that the graph cannot have self-loops; i.e. (i,i) E.) 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

9 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 12-2 For each of the following, indicate whether it would best be represented by directed graph, an undirected graph, or either: a. Vertices: the cast of characters in the soap opera; edges: “in love with”. b. Vertices: countries on a map; edges: adjacent borders. c. Vertices: countries; edges: major export markets. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

10 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 12-2 d. Vertices: devices in a computer network; edges: connectivity. e. Vertices: variables in a computer program; edges: “uses” relations. (We say variable x uses variable y if y appears on the right hand side of an expression with x on the left, e.g. x = y.) f. Vertices: football teams; edges: games during season. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

11 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 12-3 Draw a representation of the following graph: G = (V,E);V={0,1,2,3};E = {{0,3},{1,2},{2,3},{0,1}} 12-4 Draw a representation of the following graph: G = (V, E); V = {0,1,2,3}; E = {(0,1),(0,2),(0,3),(2,3),(3,0)} 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

12 Figure 12-4: An Adjacency List of Figure 12-3
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

13 Figure 12-5: An Adjacency Matrix representation of Figure 12-3
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

14 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-1 Characteristics An Undirected Adjacency List Graph G = (V,E) stores an undirected graph so that vertex neighbors can be found efficiently. The number of vertices in the graph, n = |V|, is fixed when the graph is created. The vertices are labeled 0…n-1. Operations: 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

15 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-1 int vertexSize() Precondition: None. Postcondtion: None. Returns: The number of vertices in the graph, |V|. int edgeSize() Returns: The number of edges in the graph, |E|. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

16 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-1 void addEdge(i,j) Precondition: Postcondition: int nextNeighbor(i) Postcondition: If the current iterator position is within the neighbor list, it’s advanced to the next neighbor; if it’s at the end of the neighbor list, it’s reset to the beginning. Returns: The next neighbor of i, or n if at the end of the list. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

17 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-2 Characteristics A Directed Adjacency List Graph G = (V,E) stores an directed graph so that vertex neighbors can be found efficiently. The number of vertices in the graph, n = |V|, is fixed when the graph is created. The vertices are labeled 0…n-1. Operations: 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

18 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-2 int vertexSize() Precondition: None. Postcondition: None. Returns: The number of vertices in the graph, |V|. int edgeSize() Returns: The number of edges in the graph, |E|. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

19 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-2 void addEdge(i,j) Precondition: Postcondition: int nextNeighbor(i) Postcondition: If the current iterator position is within the neighbor list, it’s advanced to the next neighbor; if it’s at the end of the neighbor list, it’s reset to the beginning. Returns: The next neighbor of i, or n if at the end of the list. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

20 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-3 Characteristics An Undirected Adjacency Matrix Graph G = (V,E) stores an undirected graph so that vertex connectivity can be queried efficiently. The number of vertices in the graph, n =|V|, is fixed when the graph is created. The vertices are labeled 0…n-1. Operations: 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

21 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-3 int vertexSize() Precondition: None. Postcondition: None. Returns: The number of vertices in the graph, |V| int edgeSize() Returns: The number of edges in the graph, |E| 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

22 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-3 void addEdge(i,j) Precondition: Postcondition: bool edgeConnected(i,j) Postcondition: None. Returns: True if and only if Note that by convention 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

23 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-4 Characteristics A Directed Adjacency Matrix Graph G = (V,E) stores an directed graph so that vertex connectivity can be queried efficiently. The number of vertices in the graph, n = |V|, is fixed when the graph is created. The vertices are labeled 0…n-1. Operations: 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

24 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-4 int vertexSize() Precondition: None. Postcondition: None. Returns: The number of vertices in the graph, |V|. int edgeSize() Returns: The number of edges in the graph, |E|. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

25 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-4 void addEdge(i,j) Precondition: Postcondition: bool edgeConnected(i,j) Postcondition: None. Returns: True if and only if Note that by convention 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

26 Copyright  1997 Oxford University Press All Rights Reserved
Exercises 12-5 Show the adjacency list and adjacency matrix representations for the graph shown in Figure 12-6. 12-6 Show the adjacency list and adjacency matrix representations for the graph shown in Figure 12-7. 12-7 Draw a representation of the graph defined by the adjacency list shown in Figure 12-8. 12-8 Draw a representation of the (undirected) graph defined by the adjacency matrix shown in Figure 12-9. 12-9 Write pseudocode for the procedure a client can use to write an edgeConnected function for an adjacency list graph. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

27 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Write pseudocode for the procedure a client can use to write a nextNeighbor function for an adjacency matrix graph. How much space does an adjacency list graph require? State your answer in big-O notation, as a function of n and m. How much space does an adjacency matrix require? State your answer in big-O notation, as a function of n and m. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

28 Figure 12-6: Undirected graph for Exercise 12-5
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

29 Figure 12-7: Directed graph for Exercise 12-6
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

30 Figure 12-8: Adjacency List for Exercise 12-7
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

31 Figure 12-9: Adjacency Matrix for Exercise 12-8
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

32 Copyright  1997 Oxford University Press All Rights Reserved
Exercise 12-13 In an adjacency matrix for an undirected graph as presented above, approximately half the storage space required by the graph is unnecessary. Explain, and suggest a modification that uses less space. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

33 Figure 12-10: Inheritance Hierarchy for Graphs
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

34 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-1 // cx12-1.h // Code Example 12-1: Header for graph hierarchy #ifndef __MB_CX12_1__ #define __MB_CX12_1__ class graph { public: graph(int size) : n(size), m(0) { } virtual int vertexSize() { return n; } virtual int edgeSize() { return m; } virtual void addEdge(int fromV, int toV) = 0; // specify abstract class protected: int n; // number of vertices int m; // number of edges }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

35 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-5 Characteristics: A List L stores items of some type, called ListElementType. The items in the List are ordered; the Lists (1,2) and (2,1) are distinct. Operations: void L.insert(ListElementType elem) Precondition: None. Postcondition: L = L with an instance of elem added to the end of L. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

36 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-5 bool L.first(ListElementType &elem) Precondition: None. Postcondition: If the list is empty, none. Otherwise, the variable elem contains the first item in L; the “next” item to be returned is the second in L. Returns: true if and only if there is at least one element in L. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

37 Copyright  1997 Oxford University Press All Rights Reserved
ADT 12-5 bool L.next(ListElementType &elem) Precondition: The “first” operation has been called at least once. Postcondition: Variable elem contains the next item in L, if there is one, and the next counter advances by one; if there is no next element, none. Returns: true if and only if there was a next item. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

38 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-2 // cx12-2.h // Code Example 12-2: Header, List class with List Iterator class #ifndef __MB_CX12_2__ #define __MB_CX12_2__ #include "dslib.h" template < class ListElementType > class ListIter; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

39 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-2 template < class ListElementType > class List { public: List() : head(0) { } virtual void insert(const ListElementType & elem); friend class ListIter < ListElementType >; protected: struct Node; typedef Node * Link; struct Node { ListElementType elem; Link next; }; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

40 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-2 Link head; }; template < class ListElementType > class ListIter { public: ListIter(const List < ListElementType > & l, ListElementType endFlag) : myList(l), myEndFlag(endFlag), iterPtr(0) { } virtual ListElementType operator++(); protected: const List < ListElementType > & myList; List < ListElementType >::Link iterPtr; ListElementType myEndFlag; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

41 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-3 // cx12-3.cpp // Code Example 12-3: Implementation, List class with List Iterator class #include "cx12-2.h" template < class ListElementType > ListElementType ListIter < ListElementType > :: operator++() { if (iterPtr == 0) iterPtr = myList.head; else iterPtr = iterPtr->next; if (iterPtr) return iterPtr->elem; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

42 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-3 return myEndFlag; } template < class ListElementType > void List < ListElementType > :: insert(const ListElementType & elem) { Link addedNode = new Node; assert(addedNode); addedNode->elem = elem; addedNode->next = head; head = addedNode; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

43 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-4 // cx12-4.h // Code Example 12-4: Header for adjacency list base class #ifndef __MB_CX12_4__ #define __MB_CX12_4__ #include "cx12-1.h" // graph base class #include "cx12-2.h" // list class typedef List < int > IntList; typedef ListIter < int > IntListIter; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

44 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-4 class ALGraph : public graph { public: ALGraph(int size) : graph(size) { vertexList = new IntList[n]; assert(vertexList); } friend class NeighborIter; protected: IntList * vertexList; }; class NeighborIter : public IntListIter { NeighborIter(const ALGraph & G, int startVertex) : IntListIter (G.vertexList[startVertex], G.n) { assert(startVertex < G.n); } #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

45 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-5 // cx12-5.h // Code Example 12-5: Header for Undirected Adjacency List Graphs #ifndef __MB_CX12_5__ #define __MB_CX12_5__ #include "cx12-4.h" class UALGraph : public ALGraph { public: UALGraph(int size) : ALGraph(size) { } virtual void addEdge(int fromV, int toV); }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

46 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-6 // cx12-6.cpp // Code Example 12-6: Implementation file for Undirected Adjacency List Graph #include "cx12-5.h" void UALGraph::addEdge(int fromV, int toV) { assert(fromV < n && fromV >= 0 && toV < n && toV >= 0); vertexList[fromV].insert(toV); vertexList[toV].insert(fromV); m++; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

47 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-7 // cx12-7.h // Code Example 12-7: Header for Directed Adjacency List Graph #ifndef __MB_CX12_7__ #define __MB_CX12_7__ #include "cx12-4.h" // ALGraph -- Adjacency List Base Class class DALGraph : public ALGraph { public: DALGraph(int size) : ALGraph(size) { } virtual void addEdge(int fromV, int toV); }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

48 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-8 // cx12-8.cpp // Code Example 12-8: Implementation file for Directed Adjacency List Graph #include "cx12-7.h" void DALGraph::addEdge(int fromV, int toV) { assert(fromV < n && fromV >= 0 && toV < n && toV >= 0); vertexList[fromV].insert(toV); m++; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

49 Copyright  1997 Oxford University Press All Rights Reserved
Exercises What is the big-O cost of checking the precondition {from V, to V} E in a single call to addEdge? If we check the precondition, what is the cost of creating the entire graph using a sequence of calls to addEdge? For the function UALGraph::addEdge, does checking the precondition {from V, to V} E require traversing one neighbor list or two? Explain. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

50 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Modify the addEdge function to check the precondition {from V, to V} E. (Hint: Use an iterator.) Assuming that addEdge does no check the precondition {from V, to V} E, what are the effects of a call to addEdge that violates the precondition? 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

51 Figure 12-11: Partial Order Example
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

52 Figure 12-12: Topsort algorithm after one step
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

53 12-13: Topsort after the second step
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

54 Figure 12-14: Graph with a cycle
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

55 Copyright  1997 Oxford University Press All Rights Reserved
Algorithm 12-1 nextLabel = 1 find all vertex with no in-edges and push them onto a stack while the stack is not empty do pop a vertex v from the stack label(v) = nextLabel add 1 to nextLabel remove all other edges from v if any neighbor of v now has no in-edge, push it onto the stack if all vertices labeled, report the labels else report that the digraph has a cycle 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

56 Figure 12-15: One Step in a Topological Sort
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

57 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 // cx12-9.cpp // Code Example 12-9: Topological Sort #include "dslib.h" #include "cx12-7.h" // directed adjacency list graphs #include "sx8-1.h" // stacks (supplemental version) #include "cx9-4.h" // queues #include <fstream.h> int main() { // read graph from a file // first entry is size of graph const char * inFileName = "graph.dat"; ifstream ifs(inFileName); assert(ifs); // make sure graph exists 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

58 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 int n; ifs >> n; DALGraph G(n); cout << "Created graph; n = " << G.vertexSize() << endl; // now read in the edges and add to the graph int u, v; while ( ifs >> u ) { ifs >> v; G.addEdge(u,v); } cout << "Edges in graph: m = " << G.edgeSize() << endl; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

59 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 // count the number of in-edges for each vertex int * vertices(new int[n]); assert(vertices); for (u = 0; u < n; u++) vertices[u] = 0; for (u = 0; u < n; u++) { NeighborIter ni(G,u); while ((v = ++ni) != n) vertices[v]++; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

60 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 // put vertices with no in-edge onto a stack Stack < int > s; for (u = 0; u < n; u++) if (vertices[u] == 0) s.push(u); if (s.isEmpty()) { cout << "graph has a cycle!\n"; return 0; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

61 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 // begin topological sort // As each vertex is identified, put it into a queue and // decrement the number of in-edges for its neighbors int count = 0; // number of vertices found so far Queue < int > sortedEdges; while (!s.isEmpty()) { count++; u = s.pop(); sortedEdges.enqueue(u); // reduce in count for u's neighbors; // for each that goes to zero, put on stack NeighborIter ni(G,u); 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

62 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-9 while ((v = ++ni) != n) { --vertices[v]; if (vertices[v] == 0) s.push(v); } // check results if (count < n) cout << "Couldn't complete top sort -- cycle present.\n"; cout << "Ordering for top sort: \n"; while (!sortedEdges.isEmpty()) cout << sortedEdges.dequeue() << '\t'; cout << endl; return n; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

63 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Explain the relationship between the Topsort algorithm and the example in Section 12.1 on Page Test the Topsort program using the graph in Figure 12-1. Analyze the run time of Topsort, as a function of n and m. Prove that if a directed graph does not have a cycle, then there has to be a vertex with no in-edges. (Hint: assume the contrary and show contradiction.) In general, a graph has more than one possible Topsort ordering. Propose an algorithm that will list all legal Topsorts. (Hint: use recursion.) 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

64 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-10 // cx12-10.h // Code Example 12-10: Header for adjacency matrix base class #ifndef __MB_CX12_10__ #define __MB_CX12_10__ #include "dslib.h" #include "cx12-1.h" // graph base class class amGraph : public graph { public: amGraph(int size); virtual bool edgeMember(int fromV, int toV); protected: int * * am; // am points to pointers to int }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

65 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-11 // cx12-11.cpp // Code Example 12-11: Implementation for adjacency matrix base class #include "cx12-10.h" amGraph::amGraph(int size) : graph(size) { int i; am = new int * [n]; // make an array of pointers to int assert(am); 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

66 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-11 for (i = 0; i < n; i++) { am[i] = new int[n]; // make an array of ints assert(am[i]); int j; for (j = 0; j < n; j++) // initialize the array to 0 am[i][j] = 0; } bool amGraph::edgeMember(int fromV, int toV) { assert (fromV < n && toV < n && fromV >= 0 && toV >= 0); return bool(am[fromV][toV] != 0); 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

67 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-12 // cx12-12.h // Code Example 12-12: Header for directed adjacency matrix class #ifndef __MB_CX12_12__ #define __MB_CX12_12__ #include "cx12-10.h" // adjacency matrix base class class dAMGraph : public amGraph { public: dAMGraph(int size, int initialValue = 0) : amGraph(size) { } virtual void addEdge(int fromV, int toV); }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

68 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-13 // cx12-13.cpp // Code Example 12-13: Implementation for directed adjacency matrix class #include "cx12-12.h" void dAMGraph::addEdge(int fromV, int toV) { assert(fromV < n && toV < n && fromV >= 0 && toV >= 0); if (!edgeMember(fromV, toV)) { m++; am[fromV][toV] = 1; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

69 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-14 // cx12-14.h // Code Example 12-14: Header for undirected adjacency matrix class #ifndef __MB_CX12_14__ #define __MB_CX12_14__ #include "cx12-10.h" class uAMGraph : public amGraph { public: uAMGraph(int size, int initialValue = 0) : amGraph(size) { } virtual void addEdge (int fromV, int toV); }; #endif 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

70 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-15 // cx12-15.cpp // Code Example 12-15: Implementation for undirected adjacency matrix class #include "cx12-14.h" void uAMGraph::addEdge(int fromV, int toV) { assert(fromV < n && toV < n && fromV >= 0 && toV >= 0); if (!edgeMember(fromV, toV)) { m++; am[fromV][toV] = 1; am[toV][fromV] = 1; } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

71 Figure 12-16: A Communications Network
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

72 Copyright  1997 Oxford University Press All Rights Reserved
Definitions 12-1 A sequence [v0,v1,…,vk] is a path from v0 to vk in an undirected graph G = (V,E) if and only if {vi, vj+1} E for all 1 i < k. The length of the path is k. 12-2 For a graph G = (V, E), the transitive closure graph G* = (V, E*) has edge {v1,v2} E* if and only if there's a path [v1,…,v2] in graph G. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

73 Figure 12-17: Transitive Closure of Graph from Figure 12-16
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

74 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-16 // cx12-16.cpp // Code Example 12-16: Transitive Closure #include "dslib.h" #include "cx12-14.h" #include <fstream.h> int main() { const char * inFileName = "graph2.dat"; // read graph from a file // first entry is size of graph 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

75 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-16 ifstream ifs(inFileName); assert(ifs); int n; ifs >> n; uAMGraph G(n); cout << "Created graph; n = " << G.vertexSize() << endl; int u, v; while ( ifs >> u ) { ifs >> v; G.addEdge(u,v); } 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

76 Copyright  1997 Oxford University Press All Rights Reserved
Code Example 12-16 cout << "Edges in graph: m = " << G.edgeSize() << endl; int step; for (step=0; step < n; step++) for (u = 0; u < n; u++) for (v = 0; v < n; v++) if (G.edgeMember(u,step) && G.edgeMember(step,v)) G.addEdge(u,v); // print results for (u=0; u < n; u++) { cout << u << "\t: "; cout << (G.edgeMember(u,v)? "T " : "F "); cout << endl; } return 0; 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

77 Copyright  1997 Oxford University Press All Rights Reserved
Exercises Analyze the worst-case complexity of the transitive closure algorithm. Look up the definitions of the mathematical terms transitive and closure, and explain the name “ transitive closure graph”. Prove that the n steps in the outer loop of the transitive closure algorithm are both necessary and sufficient to compute the transitive closure graph. Modify code Example so that it computes the transitive closure graph without modifying the original input graph. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

78 Copyright  1997 Oxford University Press All Rights Reserved
Chapter Summary A graph represents relationships among items. Vertices represent the items, and edges represent the relationships. In an undirected graph, an edge is a set; in a directed graph, it’s a directed pair. An adjacency list is a data structure for representing a graph, by keeping a list of the neighbor vertices of each vertex. An adjacency matrix is a data structure for representing a graph, by keeping a matrix of 0’s and 1’s in which each 1 corresponds with an edge. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

79 Copyright  1997 Oxford University Press All Rights Reserved
Chapter Summary An inheritance hierarchy can be used to represent the variations on a graph. Abstract base classes allow the programmer to specify an interface for inherited objects. Iterator classes, implemented via friend classes, provide the most flexible way to create iterators. A topological sort finds an ordering of vertices consistent with the partial order represented by the edges. Transitive closure of a graph contains an edge for every path in the original graph. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

80 Programming Laboratory Problems
12-1 In a weighted graph, a numeric value is associated with every edge. Weighted graphs have many useful applications -- for example, vertices can represent airports that a particular airline services, and the weighted edges can represent the cost of a ticket between airports that the airline flies between. a. Create an ADT for an undirected, weighted graph, represented by an adjacency matrix. Use floating point numbers for the weights. (Continued on the next slide.) 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

81 Programming Laboratory Problems
b. Write the code for your ADT, inheriting from the uAMGraph class. c. Write a simple application that simulates an airline’s graph of ticket prices. The program should read in vertices and prices, and keep an array that maps vertices to the names of the airports. Store a very high cost, representing “infinity” for each route that the airline does not fly. Once the graph is set up, the program should accept queries consisting of the names of two airports, and either report a cost, or report that no flight is available. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

82 Programming Laboratory Problems
12-2 The Depth-First Search (DFS) algorithm can be used to traverse all the vertices of a graph. DFS works as follows: Algorithm 12-2: put the initial vertex into a stack; while the stack is not empty do{ pop a vertex v from the stack; visit vertex v; push all unvisited neighbors of v onto the stack; } (Continued on the next slide.) 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

83 Programming Laboratory Problems
a. Under what conditions does the DFS algorithm visit every vertex in the graph? b. Write a program that reads in a directed graph, stores it in an adjacency list, and performs a DFS, printing each vertex as it’s visited. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

84 Programming Laboratory Problems
12-3 An Eulerian tour is a sequence of vertices that crosses every edge exactly once. For example, take a look at Figure on Page The sequence [3,0,4,2,0,1,4] is an Eulerian tour for this graph. a. (Optional:) Prove that an Eulerian tour exists if and only if the number of neighbors of every vertex is even, except for the beginning and end vertices which can have an odd number of neighbors. (Continued on the next slide.) 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

85 Programming Laboratory Problems
b. Write an algorithm that finds an Eulerian tour in a graph, if such a tour exists. c. Write a program that reads in an undirected graph, stores it in an adjacency list, and finds an Eulerian tour, or else reports that no such sequence exists. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

86 Programming Laboratory Problems
12-4 Write a program that reads in a directed graph, stores it in an adjacency list, and uses Depth-First Search (see Lab 12-2) to answer a series of connectivity queries. Each query will consist of a pair of vertices, and the program should answer “connected” if there is a path from the first vertex to the second, and “not connected” if there is no such path. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

87 Programming Laboratory Problems
12-5 Write a program based on the example in Section The program should first read a directed graph that represents a set of course prerequisites. A table should be used to map vertices to strings representing the names of the courses. Then, a series of courses should be read in, representing all the courses a particular student has completed. Finally, the program should print out all courses the student is ready to take next. 5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved

88 Figure 12-18: Sample graph for Eulerian Tour
5/14/2019 Copyright  1997 Oxford University Press All Rights Reserved


Download ppt "Copyright  1997 Oxford University Press All Rights Reserved"

Similar presentations


Ads by Google