1 / 122

Prof. Qing Wang

Lecture-10~11. Lecture Notes: Data Structures and Algorithms. Chapter 9 Graph. Prof. Qing Wang. Table of Contents. Graph Definition and Concepts Graph ADT and Storage Graph Traversal and Connectivity Mini Spanning Tree Shortest Path Topological Sorting and Critical Path Summary.

pasty
Download Presentation

Prof. Qing Wang

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture-10~11 Lecture Notes: Data Structures and Algorithms Chapter 9 Graph Prof. Qing Wang

  2. Table of Contents • Graph Definition and Concepts • Graph ADT and Storage • Graph Traversal and Connectivity • Mini Spanning Tree • Shortest Path • Topological Sorting and Critical Path • Summary Prof. Q.Wang

  3. 9.1 Graph Definition and Concepts • Graph • Consists of a set, whose members are called the vertices of G, together with a set E of pairs of distinct vertices from G. • Vertices set • Edge (arc) set Graph=( V, E ) V = { x | x  Data Object} E = {(x, y) | x, y V } E = {<x, y> | x, y V && Path (x, y)} Prof. Q.Wang

  4. Examples Prof. Q.Wang

  5. Concepts • Vertex • Arc • Tail or Initial node • Head or Terminal node • Edge v1 v2 G1 v3 v4 v1 v2 G1=(V1,{A1}) V1={v1,v2,v3,v4} A1={<v1,v2>,<v1,v3>,<v3,v4>,<v4,v1>} G2 v3 v4 v5 G2=(V2,{E2}) V2={v1,v2,v3,v4,v5} E2={(v1,v2),(v1,v4),(v2,v3),(v2,v5),(v3,v4),(v3,v5)} Prof. Q.Wang

  6. Directed graph • Ordered pair <x,y> • Undirected graph • Unordered pair (x,y) • Network • Weighted pair <x,y> or (x,y) Prof. Q.Wang

  7. Completed graph • Completed directed graph • Completed undirected graph • Sparse graph • Dense graph • Sub-graph Prof. Q.Wang

  8. Adjacent • Incident • Degree TD(v) • In Degree ID(v) • Out Degree OD(v) TD(v)=ID(v)+OD(v) Prof. Q.Wang

  9. Path • Cycle • Simple path • Simple Cycle • Path Length • Generic length • Weighted length • Connected graph • Connected component • Max connected sub-graph • Strongly connected component • Weakly connected component Prof. Q.Wang

  10. Prof. Q.Wang

  11. Spanning tree • Connected graph • Mini connected sub-graph • Have all the vertices of graph (n) • Only n-1 edges • Without cycle • Spanning forest • Unconnected graph or directed graph • Directed spanning trees A B C A D F B C F E D E Prof. Q.Wang

  12. 9.2 ADT and Storage of Graph class Graph { public: Graph ( ); voidInsertVertex ( Type & vertex ); voidInsertEdge( intv1, intv2, intweight ); voidRemoveVertex ( intv ); voidRemoveEdge ( intv1, intv2 ); intIsEmpty ( ); TypeGetWeight ( int v1, int v2 ); intGetFirstNeighbor ( int v ); intGetNextNeighbor ( intv1, intv2 ); } Prof. Q.Wang

  13. Multi-linked list v1 v2 v1 v2 G1 G2 v3 v3 v4 v4 v5 v1 v1 v2 v4 v2 v3 v3 v4 v5 Prof. Q.Wang

  14. Adjacency Matrix • Graph A = (V, E) • n vertices A.vertex[n] • A.edge[n][n] • Symmetric for undirected graph Prof. Q.Wang

  15. Degree and adjacency matrix Prof. Q.Wang

  16. Network Prof. Q.Wang

  17. // Graph class by adjacency matrix const int MaxEdges = 50; const int MaxVertices = 10; template <class NameType, class DistType> classGraph { private: SeqList<NameType>VerticesList (MaxVertices); DistType Edge[MaxVertices][MaxVertices]; int CurrentEdges; intFindVertex ( SeqList<NameType> & L; const NameType &vertex ) { return L.Find (vertex); } Prof. Q.Wang

  18. intGetVertexPos ( Const NameType &vertex ) { returnFindVertex (VerticesList, vertex );} public: Graph ( intsz = MaxNumEdges ); intGraphEmpty ( ) const { return VerticesList.IsEmpty ( );} int GraphFull( ) const{ returnVerticesList.IsFull( ) || CurrentEdges ==MaxEdges;} intNumberOfVertices ( ) { returnVerticesList.last +1;} intNumberOfEdges ( ) { returnCurrentEdges;} Prof. Q.Wang

  19. NameType GetValue ( inti ) { returni >= 0 &&i <= VerticesList.last ?VerticesList.data[i] :NULL;} DistType GetWeight ( intv1, intv2 ); intGetFirstNeighbor ( intv ); intGetNextNeighbor ( intv1, int v2 ); void InsertVertex ( NameType &vertex ); voidInsertEdge ( int v1, int v2, DistTypeweight ); voidRemoveVertex ( int v ); voidRemoveEdge ( intv1, intv2 ); } Prof. Q.Wang

  20. //Implementation of functions //constructor template <class NameType, class DistType> Graph<NameType, DistType> :: Graph( int sz) { for ( int i = 0;i < sz;i++ ) for ( intj = 0;j < sz;j++ ) Edge[i][j] = 0; CurrentEdges = 0; } //get the weight of arc (v1, v2) template <class NameType, class DistType> DistType Graph<NameType, DistType> :: GetWeight( int v1, int v2 ) { Prof. Q.Wang

  21. if ( v1 != -1 &&v2 != -1 ) returnEdge[v1][v2]; else return 0; } //Get the first adjacent node template <class NameType, class DistType> intGraph<NameType, DistType>:: GetFirstNeighbor ( const intv ) { if ( v != -1 ) { for ( intcol = 0;col < VerticesList.last;col++ ) if ( Edge[v][col] > 0 && Edge[v][col] < max ) returncol; } Prof. Q.Wang

  22. return-1; } //Get the next adjacent of v1 after v2 template <class NameType, class DistType> int Graph<NameType, DistType> :: GetNextNeighbor ( intv1, intv2 ) { intcol; if ( v1 != -1 &&v2 != -1 ) { for ( col = v2+1;col < VerticesList.last;col++ ) if ( Edge[v1][col] > 0 && Edge[v1][col] < max ) return col; } return-1; } Prof. Q.Wang

  23. Adjacency List • Undirected graph Prof. Q.Wang

  24. Out arcs In arcs Adjacency list Reverse adjacency list • Directed graph • Adjacency list • Reverse adjacency list Prof. Q.Wang

  25. Network • Adjacency list • Reverse adjacency list Adjacency list Prof. Q.Wang

  26. //Graph class by adjacency list const intDefaultSize = 10; template <class DistType> classGraph; template <class DistType> struct Edge { friend classGraph<NameType, DistType>; intdest; DistTypecost; Edge<DistType> *link; Edge ( ) { } Edge ( int D, DistTypeC ) : dest (D), cost (C), link (NULL) { } int operator != ( Edge<DistType>& E ) const { returndest != E.dest;} } Prof. Q.Wang

  27. template <class NameType, class DistType> structVertex{ friend classGraph<NameType, DistType>; NameType data; Edge<DistType> *adj; } template <class NameType, class DistType> class Graph { private: Vertex<NameType, DistType> *NodeTable; intNumVertices; intMaxVertices; int NumEdges; Prof. Q.Wang

  28. int GetVertexPos ( NameType & vertex ); public: Graph ( intsz ); ~Graph ( ); intGraphEmpty ( ) const { return NumVertices == 0;} int GraphFull ( ) const { returnNumVertices == MaxVertices;} NameType GetValue ( int i ) { returni >= 0 &&i < NumVertices? NodeTable[i].data: NULL;} intNumberOfVertices ( ) { return NumVertices;} intNumberOfEdges ( ) { returnNumEdges;} Prof. Q.Wang

  29. void InsertVertex ( NameType &vertex ); voidRemoveVertex ( intv ); voidInsertEdge ( int v1, int v2, DistTypeweight ); voidRemoveEdge ( int v1, int v2 ); DistType GetWeight ( int v1, int v2 ); intGetFirstNeighbor ( int v ); intGetNextNeighbor ( int v1, intv2 ); } Prof. Q.Wang

  30. template <class NameType, class DistType> //Constructor Graph<NameType, DistType> :: Graph ( intsz = DefaultSize ) : NumVertices (0), MaxVertices (sz), NumEdges (0){ intn, e, k, j;NameTypename, tail, head; DistTypeweight; NodeTable = newVertex<Nametype>[MaxVertices]; cin >> n; for ( inti = 0; i < n;i++) {cin >> name;InsertVertex ( name );} cin >> e; for ( i = 0;i < e; i++) { cin >> tail >> head >> weight; k = GetVertexPos ( tail );j = GetVertexPos ( head ); InsertEdge ( k, j, weight ); } } Prof. Q.Wang

  31. //Deconstructor template <class NameType, class DistType> Graph<NameType, DistType> :: ~Graph ( ) { for ( inti = 0;i < NumVertices;i++ ) { Edge<DistType> *p = NodeTable[i].adj; while ( p != NULL ) { NodeTable[i].adj = p→link;deletep; p = NodeTable[i].adj; } } delete [ ] NodeTable; } Prof. Q.Wang

  32. //Implementation of functions //get the serial number ofvertex template <class NameType, class DistType> intGraph<NameType, DistType> :: GetVertexPos ( const NameType &vertex ) { for ( inti =0; i < NumVertices;i++ ) if ( NodeTable[i].data == vertex ) returni; return-1; } Prof. Q.Wang

  33. //Get the first adjacent ofv template <Class NameType, class DistType> intGraph<NameType, DistType> :: GetFirstNeighbor ( int v ) { if ( v != -1 ) { Edge<DistType> *p = NodeTable[v].adj; if ( p != NULL ) returnp→dest; } return-1; } Prof. Q.Wang

  34. //Get the next adjacent ofv1 afterv2 template <Class NameType, class DistTypeType> intGraph<NameType, DistType> :: GetNextNeighbor ( intv1, int v2 ) { if ( v1 != -1 ) { Edge<DistType> *p = NodeTable[v1].adj; while ( p != NULL ) { if ( p→dest == v2 &&p→link != NULL ) returnp→link→dest; elsep = p→link; } } return-1; } Prof. Q.Wang

  35. //Get the cost betweenv1 andv2 template <Class NameType, class DistType> DistType Graph<NameType, DistType> :: GetWeight ( int v1, int v2) { if ( v1 != -1 &&v2 != -1 ) { Edge<DistType> *p = NodeTable[v1].adj; while ( p != NULL ) { if ( p→dest == v2) returnp→cost; elsep = p→link; } } return 0; } Prof. Q.Wang

  36. Adjacency Multi-list • Undirected graph • Edge • Mark • Vertex1, Vertex2 • Path1, Path2 (pointers to next edge incident with vertex1 or vertex2) • Vertex mark vertex1 vertex2 path1 path2 data Firstout Prof. Q.Wang

  37. Example1 of AML Prof. Q.Wang

  38. Directed graph • Edge • Mark • Vertex1 (initial node) • Vertex2 (terminal node) • Path1 (link to next arc beginning from vertex1) • Path2 (link to next arc ending at vertex2) • Vertex • Data • Firstin (point to the first arc starting from this vertex) • Firstout (point to the first arc ending at this vertex) mark vertex1 vertex2 path1 path2 data Firstin Firstout Prof. Q.Wang

  39. Example2 of AML Prof. Q.Wang

  40. Cross linked list mark tailvex headvex hlink tlink 0 1 v1 v2 data Firstin Firstout 2 3 v3 v4 0 v1 m 0 1 m 0 2 1 v2 2 v3 m 2 0 m 2 3 3 v4 m 3 0 m 3 1 m 3 2 Prof. Q.Wang

  41. 9.3 Traversal and Connectivity • Traversal • Requirement • Visit each vertex one time and only one time • Approaches • Depth-first traversal • Breadth-first traversal • Auxiliary Boolean array • Visited[] Prof. Q.Wang

  42. Depth First Search (DFS) • Steps • Searching • Backtracking (recursion involved) Searching Backtracking Prof. Q.Wang

  43. // DFS algorithm template<class NameType, class DistType> voidGraph <NameType, DistType> :: DFS ( ) { int * visited = newint [NumVertices]; for ( inti = 0;i < NumVertices;i++ ) visited [i] = 0; DFS (0, visited ); delete [ ] visited; } template<class NameType, class DistType> voidGraph<NameType, DistType> :: DFS ( const intv, int visited [ ] ) { Prof. Q.Wang

  44. cout << GetValue (v) << ‘ ’; //visit v visited[v] = 1; //markingv intw = GetFirstNeighbor (v); //Get the first adjacent of v : w while ( w != -1 ) { if ( !visited[w] ) DFS ( w, visited ); //if w has not been visited, DFS(w) w = GetNextNeighbor ( v, w ); //Get the next adjacent of v afterw } } • Time Analysis • O(n+e) for adjacency list • O(n2) for adjacency matrix Prof. Q.Wang

  45. Breadth First Search (BFS) • Steps • Search • Search in next level (queue involved) Searching Prof. Q.Wang

  46. //BFS algorithm template<class NameType, class DistType> voidGraph <NameType, DistType> :: BFS ( intv ) { int * visited = new int[NumVertices]; for ( inti = 0;i < NumVertices;i++ ) visited[i] = 0; cout << GetValue (v) << ' '; visited[v] = 1; Queue<int> q;q.EnQueue (v); while ( !q.IsEmpty ( ) ) { v = q.DeQueue ( ); intw = GetFirstNeighbor (v); Prof. Q.Wang

  47. while ( w != -1 ) { if ( !visited[w] ) { cout << GetValue (w) << ‘ ’; visited[w] = 1;q.EnQueue (w); } w = GetNextNeighbor (v, w); } } delete [ ] visited; } • Time Analysis • d0 + d1 + … + dn-1 = O(e) for adjacency list, di is the degree of node i • O(n2) for adjacency matrix Prof. Q.Wang

  48. Connected component • Connected graph • Visit all the nodes within one searching • Spanning tree • Depth first spanning tree • Breadth first spanning tree • Unconnected graph • Call DFS or BFS several times until all the nodes have been visited • Spanning forest Prof. Q.Wang

  49. Unconnected graph Example 0 A 4 3 2 1 1 B 5 0 2 C 0 3 D 0 4 E 6 5 0 5 F 6 4 1 6 G 5 4 7 H 9 8 8 I 9 7 9 J 8 7 10 K 13 12 11 11 L 14 10 12 M 14 10 13 N 10 Connected components of the unconnected graph 14 O 12 11 Prof. Q.Wang

  50. //Connected components template<class NameType, class DistType> voidGraph<NameType, DistType> :: Components ( ) { int *visited = new int[NumVertices]; for ( int i = 0; i < NumVertices;i++ ) visited[i] = 0; for ( i = 0;i < NumVertices;i++ ) if ( !visited[i] ) { DFS ( i, visited ); OutputNewComponent ( ); //output a connected component } delete [ ] visited; } Prof. Q.Wang

More Related