Graphs CS 400/600 – Data Structures. Graphs2 Graphs  Used to represent all kinds of problems Networks and routing State diagrams Flow and capacity.

Slides:



Advertisements
Similar presentations
Lecture 15. Graph Algorithms
Advertisements

IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture10.
Topological Sort Topological sort is the list of vertices in the reverse order of their finishing times (post-order) of the depth-first search. Topological.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
Graphs Chapter 12. Chapter Objectives  To become familiar with graph terminology and the different types of graphs  To study a Graph ADT and different.
Fundamentals of Python: From First Programs Through Data Structures
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
Data Structures Using C++
Data Structure and Algorithms (BCS 1223) GRAPH. Introduction of Graph A graph G consists of two things: 1.A set V of elements called nodes(or points or.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
Graph Traversals Reading Material: Chapter 9. Graph Traversals Some applications require visiting every vertex in the graph exactly once. The application.
CS 311 Graph Algorithms. Definitions A Graph G = (V, E) where V is a set of vertices and E is a set of edges, An edge is a pair (u,v) where u,v  V. If.
Greedy Algorithms Reading Material: Chapter 8 (Except Section 8.5)
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
Spring 2010CS 2251 Graphs Chapter 10. Spring 2010CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs.
Graphs. Graphs Many interesting situations can be modeled by a graph. Many interesting situations can be modeled by a graph. Ex. Mass transportation system,
CS 206 Introduction to Computer Science II 11 / 05 / 2008 Instructor: Michael Eckmann.
Fall 2007CS 2251 Graphs Chapter 12. Fall 2007CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs To.
Greedy Algorithms Like dynamic programming algorithms, greedy algorithms are usually designed to solve optimization problems Unlike dynamic programming.
More Graph Algorithms Weiss ch Exercise: MST idea from yesterday Alternative minimum spanning tree algorithm idea Idea: Look at smallest edge not.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
Course notes CS2606: Data Structures and Object-Oriented Development Graphs Department of Computer Science Virginia Tech Spring 2008 (The following notes.
Minimum Spanning Trees
UNCA CSCI November, 2001 These notes were prepared by the text’s author Clifford A. Shaffer Department of Computer Science Virginia Tech Copyright.
Theory of Computing Lecture 10 MAS 714 Hartmut Klauck.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
Charles Lin. Graph Representation Graph Representation DFS DFS BFS BFS Dijkstra Dijkstra A* Search A* Search Bellman-Ford Bellman-Ford Floyd-Warshall.
SPANNING TREES Lecture 21 CS2110 – Spring
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}
Chapter 2 Graph Algorithms.
Fundamentals, Terminology, Traversal, Algorithms Graph Algorithms Telerik Algo Academy
Chapter 14 Graphs. © 2004 Pearson Addison-Wesley. All rights reserved Terminology G = {V, E} A graph G consists of two sets –A set V of vertices,
CS200 Algorithms and Data StructuresColorado State University Part 10. Graphs CS 200 Algorithms and Data Structures 1.
COSC 2007 Data Structures II Chapter 14 Graphs III.
Minimum Spanning Trees CSE 2320 – Algorithms and Data Structures Vassilis Athitsos University of Texas at Arlington 1.
Graphs. Definitions A graph is two sets. A graph is two sets. –A set of nodes or vertices V –A set of edges E Edges connect nodes. Edges connect nodes.
SPANNING TREES Lecture 20 CS2110 – Fall Spanning Trees  Definitions  Minimum spanning trees  3 greedy algorithms (incl. Kruskal’s & Prim’s)
Graphs. Graphs Similar to the graphs you’ve known since the 5 th grade: line graphs, bar graphs, etc., but more general. Those mathematical graphs are.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 13: Graphs Data Abstraction & Problem Solving with C++
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
Graphs Slide credits:  K. Wayne, Princeton U.  C. E. Leiserson and E. Demaine, MIT  K. Birman, Cornell U.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
SPANNING TREES Lecture 21 CS2110 – Fall Nate Foster is out of town. NO 3-4pm office hours today!
Minimum- Spanning Trees
Graphs Upon completion you will be able to:
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
1 GRAPHS – Definitions A graph G = (V, E) consists of –a set of vertices, V, and –a set of edges, E, where each edge is a pair (v,w) s.t. v,w  V Vertices.
1 Data Structures and Algorithms Graphs. 2 Graphs Basic Definitions Paths and Cycles Connectivity Other Properties Representation Examples of Graph Algorithms:
Graph Search Applications, Minimum Spanning Tree
Graphs Chapter 20.
Graphs Representation, BFS, DFS
Minimum Spanning Trees
C.Eng 213 Data Structures Graphs Fall Section 3.
Common final examinations
I206: Lecture 15: Graphs Marti Hearst Spring 2012.
CS202 - Fundamental Structures of Computer Science II
CS120 Graphs.
Short paths and spanning trees
Graphs Representation, BFS, DFS
Minimum Spanning Tree.
Graphs Chapter 13.
Graphs.
CSCI 333 Graphs Chapter 11 20, 22, and 25 November 2002.
Chapter 11 Graphs.
Spanning Trees Lecture 20 CS2110 – Spring 2015.
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
GRAPH – Definitions A graph G = (V, E) consists of
INTRODUCTION A graph G=(V,E) consists of a finite non empty set of vertices V , and a finite set of edges E which connect pairs of vertices .
More Graphs Lecture 19 CS2110 – Fall 2009.
Presentation transcript:

Graphs CS 400/600 – Data Structures

Graphs2 Graphs  Used to represent all kinds of problems Networks and routing State diagrams Flow and capacity

Graphs3 Graph Definitions  A graph G = (V, E) consists of a set of vertices V, and a set of edges E Each edge is connection between two vertices  A graph can be directed or undirected, weighted or unweighted, labeled or unlabeled. A E C D B V = {A, B, C, D, E} E = {(A,B), (B,D), (B,E), (D,A), (E,C)} |V| = # of vertices, |E| = # of edges.

Graphs4 More definitions  Adjacent vertices are joined by an edge  A path from v 1 to v n exists if there are edges from v 1 to v 2 to … to v n. Simple path – all vertices distinct A cycle is a path from a vertex to itself

Graphs5 Connected Components An undirected graph is connected if there is at least one path from any vertex to any other. The maximum connected subgraphs of an undirected graph are called connected components.

Graphs6 Directed Representation Adjacency matrix: |V| by |V| Adjacency list: a linked list of edges for each vertex.

Graphs7 Undirected Representation Generally the same representations as for digraphs, but edges are entered in both directions.

Graphs8 Representation Costs  Adjacency matrix: O(|V| 2 )  Adjacency list: O(|V| + |E|)  |E| can be as low as 0, or as high as |V| 2  The best representation depends on how densely connected the graph is (i.e. how many edges there are).

Graphs9 Graph ADT class Graph { // Graph abstract class public: virtual int n() =0; // # of vertices virtual int e() =0; // # of edges // Return index of first, next neighbor virtual int first(int) =0; virtual int next(int, int) =0; // Store new edge (from, to, weight) virtual void setEdge(int, int, int) =0; // Delete edge defined by two vertices virtual void delEdge(int, int) =0; // Weight of edge connecting two vertices virtual int weight(int, int) =0; virtual int getMark(int) =0; virtual void setMark(int, int) =0; };

Graphs10 Graph Traversals Some applications require visiting every vertex in the graph exactly once. The application may require that vertices be visited in some special order based on graph topology. Examples: Artificial Intelligence Search Shortest paths problems

Graphs11 Graph Traversals (2) To insure visiting all vertices: void graphTraverse(const Graph* G) { for (v=0; v n(); v++) G->setMark(v, UNVISITED); // Initialize for (v=0; v n(); v++) if (G->getMark(v) == UNVISITED) doTraverse(G, v); } We can’t just follow edges, because the graph may not be connected, and it may include cycles.

Graphs12 Depth First Search (1) // Depth first search void DFS(Graph* G, int v) { PreVisit(G, v); // Take action G->setMark(v, VISITED); for (int w=G->first(v); w n(); w = G->next(v,w)) if (G->getMark(w) == UNVISITED) DFS(G, w); PostVisit(G, v); // Take action }

Graphs13 Depth First Search (2) Cost:  (|V| + |E|).

Graphs14 Depth First Search (3)

Graphs15 Breadth First Search (1) Like DFS, but replace stack with a queue. Visit vertex’s neighbors before continuing deeper in the tree.

Graphs16 Breadth First Search (2) void BFS(Graph* G, int start,Queue *Q) { int v, w; Q->enqueue(start); // Initialize Q G->setMark(start, VISITED); while (Q->length() != 0) { // Process Q Q->dequeue(v); PreVisit(G, v); // Take action for(w=G->first(v);w n();w=G->next(v,w)) if (G->getMark(w) == UNVISITED) { G->setMark(w, VISITED); Q->enqueue(w); } PostVisit(G, v); // Take action }

Graphs17 Breadth First Search (3)

Graphs18 Breadth First Search (4)

Graphs19 Topological Sort (1) Problem: Given a set of jobs, courses, etc., with prerequisite constraints, output the jobs in an order that does not violate any of the prerequisites.

Graphs20 Topological Sort (2) void topsort(Graph* G) { // Topological sort int i; for (i=0; i n(); i++) // Initialize G->setMark(i, UNVISITED); for (i=0; i n(); i++) // Do vertices if (G->getMark(i) == UNVISITED) tophelp(G, i); // Call helper } void tophelp(Graph* G, int v) { // Process v G->setMark(v, VISITED); for (int w=G->first(v); w n(); w = G->next(v,w)) if (G->getMark(w) == UNVISITED) tophelp(G, w); printout(v); // PostVisit for Vertex v }

Graphs21 Topological Sort (3)  Algorithm prints: J7, J5, J4, J6, J2, J3, J1  Sort: J1, J3, J2, J6, J4, J5, J7

Graphs22 Shortest Paths Problems Input: A graph with weights or costs associated with each edge. Output: The list of edges forming the shortest path. Sample problems: Find shortest path between two named vertices Find shortest path from S to all other vertices Find shortest path between all pairs of vertices We will actually calculate only distances.

Graphs23 Shortest Paths Definitions d(A, B) = the shortest distance (so far) from vertex A to B. w(A, B) = the weight of the edge connecting A to B. If there is no such edge, then w(A, B) = .

Graphs24 Dijkstra’s Algorithm  D(x) = distance from s to x (initially all  ) 1.Select the closest vertex to s, according to the current estimate (call it c) 2.Recompute the estimate for every other vertex, x, as the MINIMUM of: 1.The current distance, or 2.The distance from s to c, plus the distance from c to x – D(c) + W(c, x)

Graphs25 Dijkstra’s Algorithm Example ABCDE Initial0  Process A  Process C Process B Process D Process E A B CE D

Graphs26 Dijkstra’s Implementation // Compute shortest path distances from s, // return them in D void Dijkstra(Graph* G, int* D, int s) { int i, v, w; for (i=0; i n(); i++) { // Do vertices v = minVertex(G, D); if (D[v] == INFINITY) return; G->setMark(v, VISITED); for (w=G->first(v); w n(); w = G->next(v,w)) if (D[w] > (D[v] + G->weight(v, w))) D[w] = D[v] + G->weight(v, w); }

Graphs27 Implementing minVertex // Find min cost vertex int minVertex(Graph* G, int* D) { int i, v; // Set v to an unvisited vertex for (i=0; i n(); i++) if (G->getMark(i) == UNVISITED) { v = i; break; } // Now find smallest D value for (i++; i n(); i++) if ((G->getMark(i) == UNVISITED) && (D[i] < D[v])) v = i; return v; } How else might we get the minimum distance vertex for each iteration?

Graphs28 All-Pairs Shortest Paths For every vertex u, v  V, calculate d(u, v). Could run Dijkstra’s Algorithm |V| times. Better is Floyd’s Algorithm. Define a k-path from u to v to be any path whose intermediate vertices all have indices less than k.

Graphs29 Floyd’s Algorithm //Floyd's all-pairs shortest paths algorithm void Floyd(Graph* G) { int D[G->n()][G->n()]; // Store distances for (int i=0; i n(); i++) // Initialize for (int j=0; j n(); j++) D[i][j] = G->weight(i, j); // Compute all k paths for (int k=0; k n(); k++) for (int i=0; i n(); i++) for (int j=0; j n(); j++) if (D[i][j] > (D[i][k] + D[k][j])) D[i][j] = D[i][k] + D[k][j]; }

Graphs30 Minimal Cost Spanning Trees Minimal Cost Spanning Tree (MST) Problem: Input: An undirected, connected graph G. Output: The subgraph of G that 1) has minimum total cost as measured by summing the values of all the edges in the subset, and 2) keeps the vertices connected.

Graphs31 MST Example

Graphs32 Prim’s Algorithm  Pick any starting vertex N  Pick the least-cost edge from N to new vertex M, add (N, M) to the tree  Repeat: Pick the least cost edge from any vertex in the tree to any vertex not in the tree Add it to the tree  Until done

Graphs33 Prim’s MST Algorithm void Prim(Graph* G, int* D, int s) { int V[G->n()]; // Who's closest int i, w; for (i=0; i n(); i++) {// Do vertices int v = minVertex(G, D); G->setMark(v, VISITED); if (v != s) AddEdgetoMST(V[v], v); if (D[v] == INFINITY) return; for (w=G->first(v); w n(); w = G->next(v,w)) if (D[w] > G->weight(v,w)) { D[w] = G->weight(v,w);// Update dist V[w] = v; // Update who it came from }

Graphs34 Implementing Prim’s A ABCDEFABCDEF Mark: V[]: D[]: 00 A 079079 AAAAAA C ACCCACACCCAC D ACCDACACCDAC F ACCDFFACCDFF E ACCDEFACCDEF B ABCDEFABCDEF

Graphs35 Implementing minVertex  Same issues as Dijkstra’s algorithm: How to get the minimum distance vertex at each step Not from the source, but from any node in the tree so far

Graphs36 Kruskal’s MST Algorithm (1)

Graphs37 Kruskal’s MST Algorithm (2) Initially, each vertex is in its own MST. Merge two MST’s that have the shortest edge between them. Use a priority queue to order the unprocessed edges. Grab next one at each step. How to tell if an edge connects two vertices already in the same MST? Use the UNION/FIND algorithm with parent- pointer representation.

Graphs38 Kruskal’s MST Algorithm (3) Cost is dominated by the time to remove edges from the heap. Can stop processing edges once all vertices are in the same MST Total cost:  (|V| + |E| log |E|).