Download presentation
Presentation is loading. Please wait.
1
E.G.M. PetrakisGraphs1 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 B G C E F D
2
E.G.M. PetrakisGraphs2 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 )
3
E.G.M. PetrakisGraphs3 Undirected Graphs The edges are not directed from one vertex to another G E H A B C F D
4
E.G.M. PetrakisGraphs4 Directed Graphs The edges are directed from one vertex to another G E H A B C F D
5
E.G.M. PetrakisGraphs5 G E A BC FD A D BC
6
E.G.M. PetrakisGraphs6 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 ∊ N} x < y x mod y = odd Labeled graph: labels on vertices or edges Weighted graph: weights on edges
7
E.G.M. PetrakisGraphs7 8 310 6 17 5 relation 8 310 6 17 5 1 7 13 1 5 weighted
8
E.G.M. PetrakisGraphs8 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
9
E.G.M. PetrakisGraphs9 Connected Graphs An undirected graph is connected if there is a path between any two vertices Connected components: maximally connected subgraphs 0 1 4 3 26 5 7
10
E.G.M. PetrakisGraphs10 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 b x a b c adjacent (a,b) = true adjacent (a,c) = false a b a b
11
E.G.M. PetrakisGraphs11 Build a Graph read(n);// number of nodes read and create n nodes label them from 1.. n while not eof(..) { read(node 1, node 2, w 12 ); joinwt(node 1, node 2, w 12 ); } any graph algorithm
12
E.G.M. PetrakisGraphs12 Representation of Directed Graphs 02 4 31 directed graph 11 1 1 1 1 34210 0 1 2 3 4 adjacency matrix 14 3 4 2 1 4 3 2 0 1 adjacency list
13
E.G.M. PetrakisGraphs13 Representation of Undirected Graphs 02 4 31 undirected graph adjacency list 14 0 3 1 0 4 3 2 0 1 3 4 2 1 4 2 adjacency matrix 34210 0 1 2 3 4 1 1 1 1 1 11 1 1 1 1 1
14
E.G.M. PetrakisGraphs14 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 n 2 edge (i, j) is found at matrix[i * n + j] if edge exists matrix[i * n + j] = wt otherwise matrix[i * n + j] = NOEDGE
15
E.G.M. PetrakisGraphs15 Graph Interface interface Graph { // Graph class ADT public int n(); // Number of vertices public int e(); // Number of edges public Edge first(int v); // Get first edge for vertex public Edge next(Edge w); // Get next edge for a vertex public boolean isEdge(Edge w); // True if this is an edge public boolean isEdge(int i, int j); // True if this is an edge public int v1(Edge w); // Where edge came from public int v2(Edge w); // Where edge goes to public void setEdge(int i, int j, int weight); // Set edge weight public void setEdge(Edge w, int weight); // Set edge weight public void delEdge(Edge w); // Delete edge w public void delEdge(int i, int j); // Delete edge (i, j) public int weight(int i, int j); // Return weight of edge public int weight(Edge w); // Return weight of edge public void setMark(int v, int val); // Set Mark for v public int getMark(int v); // Get Mark for v } // interface Graph
16
E.G.M. PetrakisGraphs16 Implementation: Edge Class interface Edge { // Interface for graph edges public int v1(); // Return the vertex it comes from public int v2(); // Return the vertex it goes to } // interface Edge // Edge class for Adjacency Matrix graph representation class Edgem implements Edge { private int vert1, vert2; // The vertex indices public Edgem(int vt1, int vt2) { vert1 = vt1; vert2 = vt2; } public int v1() { return vert1; } public int v2() { return vert2; } } // class Edgem
17
E.G.M. PetrakisGraphs17 Graph class: Adjacency Matrix class Graphm implements Graph { // Graph: Adjacency matrix private int[][] matrix; // The edge matrix private int numEdge; // Number of edges public int[] Mark; // The mark array public Graphm(int n) { // Constructor Mark = new int[n]; matrix = new int[n][n]; numEdge = 0; } public int n() { return Mark.length; } // Number of vertices public int e() { return numEdge; } // Number of edges
18
E.G.M. PetrakisGraphs18 Adjacency Matrix (cont.) public Edge first(int v) { // Get the first edge for a vertex for (int i=0; i<Mark.length; i++) if (matrix[v][i] != 0) return new Edgem(v, i); return null; // No edge for this vertex } public Edge next(Edge w) { // Get next edge for a vertex if (w == null) return null; for (int i=w.v2()+1; i<Mark.length; i++) if (matrix[w.v1()][i] != 0) return new Edgem(w.v1(), i); return null; // No next edge; }
19
E.G.M. PetrakisGraphs19 Adjacency Matrix (cont.) public boolean isEdge(Edge w) { // True if this is an edge if (w == null) return false; else return matrix[w.v1()][w.v2()] != 0; } public boolean isEdge(int i, int j) // True if this is an edge { return matrix[i][j] != 0; } public int v1(Edge w) // Where edge comes from { return w.v1(); } public int v2(Edge w) // Where edge goes to { return w.v2(); }
20
E.G.M. PetrakisGraphs20 Adjacency Matrix (cont.) // Set edge weight public void setEdge(int i, int j, int wt) { Assert.notFalse(wt!=0, "Cannot set weight to 0"); matrix[i][j] = wt; numEdge++; } // Set edge weight public void setEdge(Edge w, int weight) { if (w != null) setEdge(w.v1(), w.v2(), weight); }
21
E.G.M. PetrakisGraphs21 Adjacency Matrix (cont.) public void delEdge(Edge w) { // Delete edge w if (w != null) if (matrix[w.v1()][w.v2()] != 0) { matrix[w.v1()][w.v2()] = 0; numEdge--; } public void delEdge(int i, int j) { // Delete edge (i, j) if (matrix[i][j] != 0) { matrix[i][j] = 0; numEdge--; }
22
E.G.M. PetrakisGraphs22 Adjacency Matrix (cont.) public int weight(int i, int j) { // Return weight of edge if (matrix[i][j] == 0) return Integer.MAX_VALUE; else return matrix[i][j]; } public int weight(Edge w) { // Return weight of edge Assert.notNull(w, "Can't take weight of null edge"); if (matrix[w.v1()][w.v2()] == 0) return Integer.MAX_VALUE; else return matrix[w.v1()][w.v2()]; } public void setMark(int v, int val) { Mark[v] = val; } // Set Mark public int getMark(int v) { return Mark[v]; } // Get Mark } // class Graphm
23
E.G.M. PetrakisGraphs23 Implementation: Edge Class // Edge class for Adjacency List graph representation class Edgel implements Edge { private int vert1, vert2; // Indices of v1, v2 private Link itself; // Pointer to node in adj list public Edgel(int vt1, int vt2, Link it) //Constructor { vert1 = vt1; vert2 = vt2; itself = it; } public int v1() { return vert1; } public int v2() { return vert2; } Link theLink() { return itself; } // Access adj list } // class Edgel
24
E.G.M. PetrakisGraphs24 Graph Class: Adjacency List class Graphl implements Graph {// Graph: Adjacency list private GraphList[] vertex; // The vertex list private int numEdge; // Number of edges public int[] Mark; // The mark array public Graphl(int n) { // Constructor Mark = new int[n]; vertex = new GraphList[n]; for (int i=0; i<n; i++) vertex[i] = new GraphList(); numEdge = 0; }
25
E.G.M. PetrakisGraphs25 Adjacency List (cont.) public int n() { return Mark.length; } // Number of vertices public int e() { return numEdge; } // Number of edges public Edge first(int v) { // Get the first edge for a vertex vertex[v].setFirst(); if (vertex[v].currValue() == null) return null; return new Edgel(v, ((int[])vertex[v].currValue())[0], vertex[v].currLink()); }
26
E.G.M. PetrakisGraphs26 Adjacency List (cont.) public boolean isEdge(Edge e) { // True if this is an edge if (e == null) return false; vertex[e.v1()].setCurr(((Edgel)e).theLink()); if (!vertex[e.v1()].isInList()) return false; return ((int[])vertex[e.v1()].currValue())[0] == e.v2(); } public boolean isEdge(int i, int j) { // True if this is an edge GraphList temp = vertex[i]; for (temp.setFirst(); ((temp.currValue() != null) && (((int[])temp.currValue())[0] < j)); temp.next()); return (temp.currValue() != null) && (((int[])temp.currValue())[0] == j); } 110,60
27
E.G.M. PetrakisGraphs27 Adjacency List (cont.) public int v1(Edge e) { return e.v1(); } // Where edge comes from public int v2(Edge e) { return e.v2(); } // Where edge goes to public Edge next(Edge e) { // Get next edge for a vertex vertex[e.v1()].setCurr(((Edgel)e).theLink()); vertex[e.v1()].next(); if (vertex[e.v1()].currValue() == null) return null; return new Edgel(e.v1(), ((int[])vertex[e.v1()].currValue())[0], vertex[e.v1()].currLink()); } 110,60
28
E.G.M. PetrakisGraphs28 Adjacency List (cont.) public void setEdge(int i, int j, int weight) {// Set edge weight Assert.notFalse(weight!=0, "Cannot set weight to 0"); int[] currEdge = { j, weight }; if (isEdge(i, j)) // Edge already exists in graph vertex[i].setValue(currEdge); else { // Add new edge to graph vertex[i].insert(currEdge); numEdge++; } public void setEdge(Edge w, int weight) // Set edge weight { if (w != null) setEdge(w.v1(), w.v2(), weight); }
29
E.G.M. PetrakisGraphs29 Adjacency List (cont.) public int weight(int i, int j) { // Return weight of edge if (isEdge(i, j)) return ((int[])vertex[i].currValue())[1]; else return Integer.MAX_VALUE; } public int weight(Edge e) { // Return weight of edge if (isEdge(e)) return ((int[])vertex[e.v1()].currValue())[1]; else return Integer.MAX_VALUE; } public void setMark(int v, int val) { Mark[v] = val; } // Set Mark public int getMark(int v) { return Mark[v]; } // Get Mark } // class Graphl
30
E.G.M. PetrakisGraphs30 A Better Implementation ndptr: pointer to adjacent node nextarc: pointer to next edge arcptrinfonextnode info: data arcptr: pointer to an adjacent node nextnode: pointer to a graph node ndptrnextarc E A B C D
31
E.G.M. PetrakisGraphs31 AΒ nilnil CDE nilnil nilnil nilnil nilnil nilnil graph
32
E.G.M. PetrakisGraphs32 Graph Traversal Trees preorder inorder postorder Graphs Depth First Search (DFS) Breadth First Search (BFS)
33
E.G.M. PetrakisGraphs33 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) }
34
E.G.M. PetrakisGraphs34 Complexity of DFS O(|V| + |E|): adjacency list representation O(|V| 2 ) in dense graphs O(|V| 2 ): matrix representation
35
E.G.M. PetrakisGraphs35 DFS : V 1 V 2 V 4 V 8 V 5 V 6 V 3 V 7 v = v 1 v1v1 v2v2 v3v3 v4v4 v5v5 v6v6 v7v7 v8v8 v3v3 v2v2 v1v1 v6v6 v5v5 v4v4 v8v8 v7v7 2 1 1 2 2 3 3 4 3 4 6 8 8 8 8 5 5 7 7 6
36
E.G.M. PetrakisGraphs36 Breadth-First Search (BFS) ΒFS : V 1 V 2 V 3 V 4 V 5 V 6 V 7 V 8 v = v 1 v1v1 v2v2 v3v3 v4v4 v5v5 v6v6 v7v7 v8v8
37
E.G.M. PetrakisGraphs37 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 x do if ! Mark(y) { Mark(y) = TRUE; enqueue(y,Q); }
38
E.G.M. PetrakisGraphs38 v1v1 front rear v3v3 v2v2 front rear output(v 1 ) v3v3 front rear v5v5 v4v4 output(v 2 ) output(v 3 ) v4v4 front rear v7v7 v5v5 v6v6 v5v5 front rear v8v8 v6v6 v7v7 output(v 4 ) v6v6 front v7v7 v8v8 output(v 5 ) v6v6 front v8v8 output(v 6 ) output(v 7 ) v = v 1 v1v1 v2v2 v3v3 v4v4 v5v5 v6v6 v7v7 v8v8
39
E.G.M. PetrakisGraphs39 Complexity of BFS O(|V|+|E|) : adjacency list representation d 1 + d 2 +...+ d n = |E| d i = degree (v i ) O(|V| 2 ) : adjacency matrix representation
40
E.G.M. PetrakisGraphs40 DFS Algorithm static void DFS (Graph G, int v) { PreVisit(G, v); // Take appropriate action G.setMark(v, VISITED); for ( Edge w = G.first(v); G.isEdge(w); w = G.next(w)) if (G.getMark(G.v 2 (w)) = = UNVISITED) DFS ( G, G.v 2 (w)); PostVisit(G, v); // Take appropriate action }
41
E.G.M. PetrakisGraphs41 BFS Algorithm void BFS (Graph G, int start) { Queue Q(G.n( )); Q.enqueue(start); G.setMark(start, VISITED); while ( !Q.isEmpty( )){ int v = Q.dequeue( ); PreVisit(G, v); // Take appropriate action for ( Edge w = G.first(v); G.isEdge(w); w = G.next(w)) if (G.getMark(G.v 2 (w)) = = UNVISITED) { G.setMark(G.v 2 (w), VISITED); Q.enqueue(G.v 2 (w)); } PostVisit(G, v); // Take appropriate action }
42
E.G.M. PetrakisGraphs42 Connected - Unconnected A BC D E connected components E F G A B C D connected graph: undirected graph, there is a path connecting any two nodes unconnected graph: not always a path
43
E.G.M. PetrakisGraphs43 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|)
44
E.G.M. PetrakisGraphs44 Spanning Trees (G,E) Tree formed from edges and nodes of G Spanning Tree
45
E.G.M. PetrakisGraphs45 Spanning Forest Set of disjoint spanning trees T i of G=(V,E) T i = ( V i, E i ) 1≤ i ≤ k, V i,E i :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
46
E.G.M. PetrakisGraphs46 DFS DFS spanning tree D BC E A DFS C B DE A C BF E A G D D C EGF B A DFS spanning forest
47
E.G.M. PetrakisGraphs47 BFS BFS spanning tree ΒFS E BC F A D GE BC F A D G BFS spanning forest C BF E A H D C H DE F B A ΒFS
48
E.G.M. PetrakisGraphs48 Min. Cost Spanning Tree cost T = 1 + 5 + 2 + 4 + 3 3 1 1 3 6 1 4 1 3 6 1 4 42 1 23 6 1 4 5 42 1 5 23 6 1 4 5 3 42 1 5 23 6 1 4 6 5 6 6 3 42 5 5 1 Prim’s algorithm: Complexity O(|V| 2 )
49
E.G.M. PetrakisGraphs49 Prim’s Algorithm static void Prim(Graph G, int s, int[] D ){//prim’s MST algorithm int[] V = new int[G.n( )];// who’s closest for (int i=0; i<G.n( ); i++) D[i] = INFINITY; // initialize D[s] = 0; for ( i=0; i<G.n( ); i++){// process the vertices int v = minVertex(G, D); G.setMark(v], VISITED); if ( v != s ) AddEdgetoMST(V[v], v);// add this edge to MST if (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 }
50
E.G.M. PetrakisGraphs50 Prim’s Algorithm (cont.) // find min cost vertex static int minVertex(Graph G, int[] D ) { int v = 0; for (int i = 0; i < G.n( ); i++)// initialize if (G.getMark(i) == UNVISITED) { v = i; break; } for ( i=0; i<G.n( ); i++)// find smallest value if ((G.getMark(i) == UNVISITED) && ( D[i] < D[v] )) v = i; return v; }
51
E.G.M. PetrakisGraphs51 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
52
E.G.M. PetrakisGraphs52 20 1 2 3 5 4 100 10 60 50 10 30 starting point: v = 1 stepSWD(2)D(3)D(4)D(5) 1{1}-10i nfinite 30100 2{1,2}2106030100 3{1,2,4}410503090 4{1,2,4,3}310503060 5{1,2,4,3,5}510503060
53
E.G.M. PetrakisGraphs53 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
54
E.G.M. PetrakisGraphs54 Compute Shortest Path static void Dijkstra(Graph G, int s, int[] D) { 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); G.setMark(v, VISITED); if (D[v] == INFINITY) return; // remaining vertices unreachable 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); }
55
E.G.M. PetrakisGraphs55 Find Min. Cost Vertex static int minVertex(Graph G, int[] D) { int v=0; 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 )
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.