E.G.M. PetrakisGraphs1 Graph G(V,E): finite set V of nodes (vertices) plus a finite set E of arcs...
-
Upload
ashlyn-mclaughlin -
Category
Documents
-
view
218 -
download
0
Transcript of E.G.M. PetrakisGraphs1 Graph G(V,E): finite set V of nodes (vertices) plus a finite set E of arcs...
E.G.M. Petrakis Graphs 1
Graphs Graph G(V,E): finite set V of nodes
(vertices) plus a finite set E of arcs (or edges) between nodes V = {A, B, C, D, E, F, G} E = {AA, AB, AD, CD, DE, BF, EF, FG, EG }
A
BG
C
E
F
D
E.G.M. Petrakis Graphs 2
Terminology Two vertices are adjacent if they are
connected with an edge Adjacent or neighbor vertices Subgraph of G=(V,E): a graph G’=(V’,E’)
where V’, E’ are subsets of V, E |V|,|E|: number of nodes, edges of G Complete graph: contains all possible
edges |E| in Θ(|V|2)
E.G.M. Petrakis Graphs 3
Undirected Graphs
The edges are not directed from one vertex to another
GE
H
A
B
C
F
D
E.G.M. Petrakis Graphs 4
Directed Graphs
The edges are directed from one vertex to another
GE
H
A
B
C
F
D
E.G.M. Petrakis Graphs 5
G
E
A
B C
FD
A
D
B C
E.G.M. Petrakis Graphs 6
More Definitions
Vertex degree: maximum number of incoming or outgoing edges in-degree: number of incoming edges out-degree: number outgoing edges
Relation R on A: R = {<x, y>| x, y ∊ N} x < y x mod y = odd
Labeled graph: labels on vertices or edges
Weighted graph: weights on edges
E.G.M. Petrakis Graphs 7
8
3 10
6
175
relation
8
3 10
6
175
1
7
13
1 5
weighted
E.G.M. Petrakis Graphs 8
Paths
There exist edges connecting two nodes Length of path: number of edges Weighted graphs: sum of weights on path Cycle: path (of length 3 or more)
connecting a vertex with itself Cyclic graph: contains cycle Acyclic graph: does not contain cycle DAG: Directed Acyclic Graph
E.G.M. Petrakis Graphs 9
Connected Graphs
An undirected graph is connected if there is a path between any two vertices
Connected components: maximally connected subgraphs
0
1
43
2 6
5
7
E.G.M. Petrakis Graphs 10
Operations on Graphs
join (a,b) join (a,b,x) remv[wt] (a,b,x) adjacent (a,b)
a b a b
a b a bx
a b
c
adjacent (a,b) = trueadjacent (a,c) = false
a b a b
E.G.M. Petrakis Graphs 11
Build a Graph
read(n); // number of nodesread and create n nodeslabel them from 1 .. n
while not eof(..) {
read(node1, node2, w12);joinwt(node1, node2, w12);
}
any graph algorithm
E.G.M. Petrakis Graphs 12
Representation of Directed Graphs
0 2
4
31
directed graph
111
11
1
3 4210
01234
adjacency matrix1 4
3
4
2
14
3
2
0
1
adjacency list
E.G.M. Petrakis Graphs 13
Representation of Undirected Graphs
0 2
4
31
undirected graph
adjacency list
1 4
0
3
1
04
3
2
0
1 3
4
2
1
4
2
adjacency matrix
3 4210
01234
11
11
1
1 11
11 1
1
E.G.M. Petrakis Graphs 14
Matrix Implementation
Simple but difficult to process edges, unused space in matrix
mark: 1D array marking vertices mark[i] = 1 if vertex i has been visited
typedef int *Edge; matrix: the actual Graph implemented
as an 1D array of size n2
edge (i, j) is found at matrix[i*n + j] if edge exists matrix[i*n + j] = wt otherwise matrix[i*n + j] = NOEDGE
E.G.M. Petrakis Graphs 15
Graph class: Adjacency Matrix
template <class Edge> class Graph {private:
Edge* matrix; // the edge matrixint numVertex, numEdge; // number of vertices, edgesbool* Mark; // the mark array
public:Graph( ); ~Graph( ); // constructor, destructorint n( ), e ( ) // number of vertices, edgesEdge first(int); // get the first edge for a vertexbool isEdge(Edge); // TRUE if this is an edgeEdge next(Edge); // get next edge for a vertexint v1(Edge), v2(Edge) // vertex edge comes from, goes toint weight(int, int); // return weight of edgeint weight(Edge); // return weight of edge
};
E.G.M. Petrakis Graphs 16
Constructor, Destructor
template <class Edge>Graph<Edge>::Graph( ) {
mark = NULL; matrix = NULL;}
template <class Edge>Graph<Edge>::~Graph( ) {
if (mark != NULL) delete [ ] mark;if (matrix != NULL) delete [ ] matrix;
}
E.G.M. Petrakis Graphs 17
Member Functions
template <class Edge>int Graph<Edge>::n( ) { return numVertex; }
template <class Edge>int Graph<Edge>::e( ) { return numEdge; }
E.G.M. Petrakis Graphs 18
Member Functions (cont.)
template <class Edge> Edge Graph<Edge>::first(int v) { //first edge
of nodeint stop = (v+1) *numVertex; // pos. at end of v’s row
for ( int pos = v * numVertex; pos < stop; pos++) //scans entire row
if ( matrix[pos] != NOEDGE) return &matrix[pos];return NULL;
}
E.G.M. Petrakis Graphs 19
Member Functions (cont.)
template <class Edge>bool Graph<Edge>::isEdge(Edge w)
{ return w != NULL; }
template <class Edge>Edge Graph<Edge>::next(Edge w) { // next edge of
(w,0)int stop = (v1(w) + 1) * numVertex; // pos at end of rowfor (int pos = (w – matrix) + 1; pos < stop; pos++)
if (matrix[pos] != NOEDGE) return &matrix[pos];return NULL;
}
E.G.M. Petrakis Graphs 20
Member Functions (cont.)
template <class Edge>int Graph<Edge>::v1(Edge w) // 1st vertex of
edge { return ( w – matrix ) / numVertex; }
template <class Edge>int Graph<Edge>::v2(Edge w) // 2nd vertex edge
{ return ( w – matrix ) % numVertex; }
E.G.M. Petrakis Graphs 21
Member Functions (cont.)
template <class Edge>int Graph<Edge>::weight( int i, int j) { // return
weight of edgeif ( matrix[ i * numVertex + j ] == NOEDGE )
return INFINITY;else return matrix[ i * numVertex + j ]; }
template <class Edge>int Graph<Edge>::weight(Edge w) { // return weight of
edgeif ( *w == NOEDGE ) return INFINITY;else return *w;
}
E.G.M. Petrakis Graphs 22
Graph Class: Adjacency List
template <class Edge> class Graph {private:
Edge *list; // the vertex listint numVertex; // number of verticesint numEdge; // number of edgesbool *Mark; // the mark array
public:Graph( ); ~Graph( ); // constructor, destructorint n( ), e( ); // number of vertices, edgesEdge first(int); // get the first edge of vertexbool isEdge(Edge); // TRUE if this is an edgeEdge next(Edge); // get next edge for a vertexint v1(Edge), v2(Edge); // return vertex edge comes from, goes toint v2(Edge); // return vertex edge goes toint weight(int, int), // return weight of edgeint weight(weight); // return weight of edge
};
E.G.M. Petrakis Graphs 23
A Singly-Linked List Node class EdgeLink {
public:int weight; // edge weightint v1; // 1st vertex of edgeint v2; // 2nd vertex of edgeEdgeLink *next; // pointer to next edge in listEdgeLink(int vt1, int vt2, int w, EdgeLink *nxt = NULL)
// constructor{ v1 = vt; v2 = vt2; weight = w; next = nxt; }
};
Graph<EdgeLink> g;
E.G.M. Petrakis Graphs 24
Member Functionstemplate <class Edge>Graph<Edge>::Graph( ) { // constructor
Mark = NULL; list = NULL;}template <class Edge>Graph<Edge>::~Graph( ) { // destructor: return
allocated spaceif (Mark != NULL) delete [ ] Mark;if (list != NULL) { // remove all of the edges for (int v = 0; v < n( ); v++) // for each vertex return all edges
while (list[v] != NULL) { list[v]= list[v]next; delete temp;
} delete [ ] list; // remove the vertex list headers}
}
E.G.M. Petrakis Graphs 25
Member Functions (cont.)template <class Edge> int Graph<Edge>::n( ) { return numVertex; } // number of
vertices
template <class Edge>int Graph<Edge>::e( ) { return numEdge; } // number of
edges
template <class Edge>Edge Graph<Edge>::first(int v) // get the first edge
{return list[v]; }
template <class Edge>bool Graph<Edge>::isEdge(Edge w) // TRUE if it is
an edge{ return w != NULL; }
E.G.M. Petrakis Graphs 26
Member Functions (cont.)template <class Edge>Edge Graph<Edge>::next(Edge w) { // get next edge for a
vertexif (w == NULL) return NULL;else return wnext;
}
template <class Edge>int Graph<Edge>::v1(Edge w) // return vertex edge comes
from{ return wv1; }
template <class Edge>int Graph<Edge>::v2(Edge w) // return vertex edge goes to
{ return wv2; }
E.G.M. Petrakis Graphs 27
Member Functions (cont.)
template <class Edge>int Graph<Edge>::weight( int i, int j) { // return
weight of edgefor (Edge curr = list[i]; curr != NULL; curr = curr->next)
if (currv2 == j ) return curr-> weight;return INFINITY;
}
template <class Edge>int Graph<Edge>::weight(Edge w) { // return weight of
edgeif ( w == NULL ) return INFINITY;else return w -> weight;
}
E.G.M. Petrakis Graphs 28
A Better Implementation
ndptr: pointer to adjacent nodenextarc: pointer to next edge
arcptr info nextnode
info: dataarcptr: pointer to an adjacent nodenextnode: pointer to a graph node
ndptr nextarc
E
A
B
C
D
E.G.M. Petrakis Graphs 29
A Βnil
C D Enil
nil
nil
nil
nil
<C,E>
<A,E><A,D><A,C><A,B>
<D,B>
graph
E.G.M. Petrakis Graphs 30
Graph Traversal
Trees preorder inorder postorder
Graphs Depth First Search (DFS) Breadth First Search (BFS)
E.G.M. Petrakis Graphs 31
Depth First Search (DFS)
Starting from vertex v, initially all vertices are “unvisited”
void DFS(v) { Mark(v) = true; for each vertex w adjacent to v if (!Mark(w)) DFS(w)
}
E.G.M. Petrakis Graphs 32
Complexity of DFS
O(|V| + |E|): adjacency list representation O(|V|2) in dense graphs
O(|V|2): matrix representation
E.G.M. Petrakis Graphs 33
DFS : V1V2V4V8V5V6V3V7
v = v1
v1
v2 v3
v4 v5 v6 v7
v8
v3
v2
v1
v6
v5
v4
v8
v7
21122334
34688885
57
76
E.G.M. Petrakis Graphs 34
Breadth-First Search (BFS)
ΒFS : V1V2V3V4V5V6V7V8
v = v1
v1
v2 v3
v4 v5 v6v7
v8
E.G.M. Petrakis Graphs 35
BFS (cont.) Starting from vertex v, all nodes “unvisited”,
visit adjacent nodes (use a queue)void DFS(v) {
visited(v) = true;enqueue(v, Q);while ( Q ≠ 0 ) {
x = dequeue(Q);for each y adjacent xdo if ! Mark(y) { Mark(y) = TRUE;
enqueue(y,Q);}
}}
E.G.M. Petrakis Graphs 36
v1front
rearv3v2front
rear
output(v1)
v3front
rear
v5v4 output(v2)
output(v3)v4front
rear
v7v5 v6
v5front
rear
v8v6 v7 output(v4)
v6front v7 v8 output(v5)
v6front v8output(v6)
output(v7)
v = v1 v1
v2 v3
v4 v5 v6 v7
v8
E.G.M. Petrakis Graphs 37
Complexity of BFS
O(|V|+|E|) : adjacency list representation
d1 + d2 + ...+ dn = |E| di = degree (vi) O(|V|2) : adjacency matrix
representation
E.G.M. Petrakis Graphs 38
DFS Algorithm
template <class Edge>void DFS (Graph<Edge>& G, int v) { action(G,v);
G.Mark[v] = VISITED;for ( Edge w = G.first(v); G.isEdge(w); w = G.next(w))
if (G.Mark[G.v2(w)] = = UNVISITED) DFS ( G, G.v2(w));action(G,v);
}
E.G.M. Petrakis Graphs 39
BFS Algorithmtemplate <class Edge>void BFS (Graph<Edge>& G, int start) {
Queue Q(G.n( ));Q.enqueue(start);G.Mark[start] = VISITED;While ( !Q.isempty( )) { int v = Q.dequeue( );
action(G,v);for ( Edge w = G.first(v); G.isEdge(w); w = G.next(w)) if (G.Mark[G.v2(w)] = = UNVISITED) { G.Mark[G.v2(w)] = VISITED;
Q.enqueue(G.v2(w)); }
action(G,v);}
E.G.M. Petrakis Graphs 40
Connected - Unconnected
A
B C
D
E
connected components
E F
G
AB
CD
connected graph: undirected graph, there is a path connecting any two nodes
unconnected graph: not always a path
E.G.M. Petrakis Graphs 41
Connected Components
If there exist unconnected nodes in a DFS or BFS traversal of G then G is unconnected
Find all connected components: void COMP(G, n){
for i = 1 to n if Mark(i) == UNVISITED
then DFS(i) [or BFS(i)];}
Complexity: O(|V| + |E|)
E.G.M. Petrakis Graphs 42
Spanning Trees
(G,E)
Tree formed from edges and nodes of G
Spanning Tree
E.G.M. Petrakis Graphs 43
Spanning Forest
Set of disjoint spanning trees Ti of G=(V,E) Ti = ( Vi , Ei ) 1≤ i ≤ k, Vi,Ei:subsets of V, E DFS produces depth first spanning trees or
forest BFS breadth first spanning trees or forest Undirected graphs provide more traversals
produce less but short spanning trees Directed graphs provide less traversals
produce more and higher spanning trees
E.G.M. Petrakis Graphs 44
DFS
DFS spanning tree
D
B C
E
A
DFS
C
B
D E
A
C
B F
E
A
G
D
DFS
D
C
E GF
B
ADFS spanning forest
E.G.M. Petrakis Graphs 45
BFS
BFS spanning treeΒFS
E
B C
F
A
D
G E
B C
F
A
D
G
BFS spanning forestC
B F
E
A
H
D
C
H
D E
F
B
A
ΒFS
E.G.M. Petrakis Graphs 46
Min. Cost Spanning Tree
costT = 1 + 5 + 2 + 4 + 3
3
1
13
6
1
4
13
6
1
4
4 2
12 3
6
1
45
4 2
1
5
2 3
6
1
45
3 4 2
1
5
2 3
6
1
4
6
5
6
6
3 4 2
5
51Prim’s algorithm: Complexity O(|V|2)
E.G.M. Petrakis Graphs 47
Prim’s Algorithmtemplate <class Edge>void Prim(Graph<Edge>& G, int s) { / /prim’s MST algorithm
int D[G.n( )]; // distance vertexint V[G.n( )]; // who’s closestfor (int i=0; i<G.n( ); i++); D[i] = INFINITY; // initializeD[s] = 0;for ( i=0; i<G.n( ); i++) { // process the vertices
int v = minVertex(G, D);G.Mark[v] = VISITED;if ( v != s ) AddEdgetoMST(V[v], v); // add this edge to MSTif (D[v] = = INFINITY ) return; // unreachable vertices for ( Edge w = G.first(v); G.isEdge(w); w = G.next(w)) if (D[G.v2(w)] > G.weight(w)) { D[G.v2(w)] = G.weight(w); // update distance and V[G.v2(w)] = v; // who it came from }
}}
E.G.M. Petrakis Graphs 48
Prim’s Algorithm (cont.)
template <class Edge> ){ // find min cost vertexvoid minVertex(Graph<Edge>& G, int* D
int v;for (int i = 0; i < G.n( ); i++) // initialize
if (G.Mark[i] = = UNVISITED) { v = i; break; }for ( i=0; i<G.n( ); i++) // find smallest valueif ((G.Mark[i] = = UNVISITED) && ( D[i] < D[v] ))
v = i;return v;
}
E.G.M. Petrakis Graphs 49
Dijkstra’s Algorithm
Find the shortest path from a given node to every other node in a graph G no better algorithm for single ending node
Notation: G = (V,E) : input graph C[i,j] : distance between nodes i, j V : starting node S : set of nodes for which the shortest path
from v has been computed D(W) : length of shortest path from v to w
passing through nodes in S
E.G.M. Petrakis Graphs 50
20
1
2
3
5
4
10010
6050 10
30
starting point: v = 1
step S W D(2) D(3) D(4) D(5)
1 {1} - 10 infinite 30 100
2 {1,2} 2 10 60 30 100
3 {1,2,4} 4 10 50 30 90
4 {1,2,4,3} 3 10 50 30 60
5 {1,2,4,3,5}
5 10 50 30 60
E.G.M. Petrakis Graphs 51
Dijkstra’s Algorithm (cont.)
Dijkstra(G: graph, int v) { S = {1}; for i = 2 to n D[i] = C[i,j]; while (S != V) {
choose w from V-S: D[w] = minimum S = S + {w};
for each v in V–S: D[v] = min{D[v], D[w]+[w,v]}*;
}}
* If D[w]+C[w,v] < D[v] then P[v] = w: keep path in array
E.G.M. Petrakis Graphs 52
Compute Shortest Pathtemplate <class Edge>void Dijkstra(Graph<Edge>& G, int s) { int D[G.n( )]; for (int i=0; i < G.n( ); i++) // initialize D[i] = INFINITY; D[s] = 0; for (i = 0; i < G.n( ); i++) { // process the vertices int v = minVertex(G, D); if (D[v] == INFINITY) return; // remaining vertices
unreachable G.setMark(v, VISITED); for (Edge w = G.first(v); G.isEdge(w); w = G.next(w)) if (D[G.v2(w)] > (D[v] + G.weight(w))) D[G.v2(w)] = D[v] + G.weight(w); }}
E.G.M. Petrakis Graphs 53
Find Min. Cost Vertex
template <class Edge>int minVertex(Graph<Edge>& G, int* D) { int v; for (int i = 0; i < G.n( ); i++) if (G.getMark(i) == UNVISITED) { v = i; break; } for (i++; i < G.n( ); i++) // find smallest D
value if ((G.getMark(i) == UNVISITED) && (D[i] < D[v])) v = i; return v;}
minVertex: scans through the list of vertices for the min. value O(|V|) time
Complexity: O(|V|2 + |E|) = O(|V|2) since O(|E|) is O(|V|2)