1.22k likes | 1.24k Views
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.
E N D
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 Prof. Q.Wang
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
Examples Prof. Q.Wang
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
Directed graph • Ordered pair <x,y> • Undirected graph • Unordered pair (x,y) • Network • Weighted pair <x,y> or (x,y) Prof. Q.Wang
Completed graph • Completed directed graph • Completed undirected graph • Sparse graph • Dense graph • Sub-graph Prof. Q.Wang
Adjacent • Incident • Degree TD(v) • In Degree ID(v) • Out Degree OD(v) TD(v)=ID(v)+OD(v) Prof. Q.Wang
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
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
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
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
Adjacency Matrix • Graph A = (V, E) • n vertices A.vertex[n] • A.edge[n][n] • Symmetric for undirected graph Prof. Q.Wang
Degree and adjacency matrix Prof. Q.Wang
Network Prof. Q.Wang
// 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
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
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
//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
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
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
Adjacency List • Undirected graph Prof. Q.Wang
Out arcs In arcs Adjacency list Reverse adjacency list • Directed graph • Adjacency list • Reverse adjacency list Prof. Q.Wang
Network • Adjacency list • Reverse adjacency list Adjacency list Prof. Q.Wang
//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
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
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
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
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
//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
//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
//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
//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
//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
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
Example1 of AML Prof. Q.Wang
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
Example2 of AML Prof. Q.Wang
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
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
Depth First Search (DFS) • Steps • Searching • Backtracking (recursion involved) Searching Backtracking Prof. Q.Wang
// 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
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
Breadth First Search (BFS) • Steps • Search • Search in next level (queue involved) Searching Prof. Q.Wang
//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
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
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
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
//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