D ESIGN & A NALYSIS OF A LGORITHM 04 – G RAPH A LGORITHMS Informatics Department Parahyangan Catholic University.

Slides:



Advertisements
Similar presentations
Theory of Computing Lecture 6 MAS 714 Hartmut Klauck.
Advertisements

Graph Theory, DFS & BFS Kelly Choi What is a graph? A set of vertices and edges –Directed/Undirected –Weighted/Unweighted –Cyclic/Acyclic.
CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
CSE 2331/5331 Topic 11: Basic Graph Alg. Representations Undirected graph Directed graph Topological sort.
Graph Searching CSE 373 Data Structures Lecture 20.
Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u
Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u
Graphs Chapter 12. Chapter Objectives  To become familiar with graph terminology and the different types of graphs  To study a Graph ADT and different.
Breadth-First and Depth-First Search
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Carrano and Henry, © 2013.
1 Graphs: Traversal Searching/Traversing a graph = visiting the vertices of a graph by following the edges in a systematic way Example: Given a highway.
Graph Search Methods Spring 2007 CSE, POSTECH. Graph Search Methods A vertex u is reachable from vertex v iff there is a path from v to u. A search method.
CS202 - Fundamental Structures of Computer Science II
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 21: Graphs.
CPSC 311, Fall CPSC 311 Analysis of Algorithms Graph Algorithms Prof. Jennifer Welch Fall 2009.
Data Structures & Algorithms Graph Search Richard Newman based on book by R. Sedgewick and slides by S. Sahni.
Graph & BFS.
Graphs Motivation and Terminology Representations Traversals Variety of Problems.
Graphs Motivation and Terminology Representations Traversals Variety of Problems.
CPSC 411 Design and Analysis of Algorithms Set 8: Graph Algorithms Prof. Jennifer Welch Spring 2011 CPSC 411, Spring 2011: Set 8 1.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
Graph COMP171 Fall Graph / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D E A C F B Vertex Edge.
Graph & BFS Lecture 22 COMP171 Fall Graph & BFS / Slide 2 Graphs * Extremely useful tool in modeling problems * Consist of: n Vertices n Edges D.
1 Data Structures and Algorithms Graphs I: Representation and Search Gal A. Kaminka Computer Science Department.
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.
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
COMP171 Depth-First Search.
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.
CS 206 Introduction to Computer Science II 03 / 25 / 2009 Instructor: Michael Eckmann.
© 2006 Pearson Addison-Wesley. All rights reserved14 B-1 Chapter 14 (continued) Graphs.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 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.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Graphs Chapter 20 Data Structures and Problem Solving with C++: Walls and Mirrors, Frank Carrano, © 2012.
CS261 Data Structures DFS and BFS – Edge List Representation.
IS 2610: Data Structures Graph April 5, 2004.
Computer Science 112 Fundamentals of Programming II Graph Algorithms.
Graph Search Computing 2 COMP s1. P ROBLEMS ON G RAPHS What kinds of problems do we want to solve on/via graphs? Is there a simple path from A to.
Nattee Niparnan. Graph  A pair G = (V,E)  V = set of vertices (node)  E = set of edges (pairs of vertices)  V = (1,2,3,4,5,6,7)  E = ((1,2),(2,3),(3,5),(1,4),(4,
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,
D ESIGN & A NALYSIS OF A LGORITHM 03 – G RAPH T HEORY Informatics Department Parahyangan Catholic University.
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Graphs.
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.
1 Chapter 22 Elementary Graph Algorithms. 2 Introduction G=(V, E) –V = vertex set –E = edge set Graph representation –Adjacency list –Adjacency matrix.
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++
1 Directed Graphs Chapter 8. 2 Objectives You will be able to: Say what a directed graph is. Describe two ways to represent a directed graph: Adjacency.
COSC 2007 Data Structures II
Graphs Chapter 12. Chapter 12: Graphs2 Chapter Objectives To become familiar with graph terminology and the different types of graphs To study a Graph.
© 2006 Pearson Addison-Wesley. All rights reserved 14 A-1 Chapter 14 Graphs.
Topological Sort: Definition
Graph. Graph Usage I want to visit all the known famous places starting from Seoul ending in Seoul Knowledge: distances, costs Find the optimal(distance.
Chapter 20: Graphs. Objectives In this chapter, you will: – Learn about graphs – Become familiar with the basic terminology of graph theory – Discover.
Graphs + Shortest Paths David Kauchak cs302 Spring 2013.
Data Structures and Algorithm Analysis Graph Algorithms Lecturer: Jing Liu Homepage:
Main Index Contents 11 Main Index Contents Graph Categories Graph Categories Example of Digraph Example of Digraph Connectedness of Digraph Connectedness.
GRAPH ALGORITHM. Graph A pair G = (V,E) – V = set of vertices (node) – E = set of edges (pairs of vertices) V = (1,2,3,4,5,6,7) E = ( (1,2),(2,3),(3,5),(1,4),(4,5),(6,7)
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.
Nattee Niparnan. Graph  A pair G = (V,E)  V = set of vertices (node)  E = set of edges (pairs of vertices)  V = (1,2,3,4,5,6,7)  E = ((1,2),(2,3),(3,5),(1,4),(4,
Brute Force and Exhaustive Search Brute Force and Exhaustive Search Traveling Salesman Problem Knapsack Problem Assignment Problem Selection Sort and Bubble.
Brute Force and Exhaustive Search Brute Force and Exhaustive Search Traveling Salesman Problem Knapsack Problem Assignment Problem Selection Sort and Bubble.
Graphs Representation, BFS, DFS
Graph Searching.
Depth-First Search.
CS202 - Fundamental Structures of Computer Science II
Search Related Algorithms
Chapter 11 Graphs.
Presentation transcript:

D ESIGN & A NALYSIS OF A LGORITHM 04 – G RAPH A LGORITHMS Informatics Department Parahyangan Catholic University

M OTIVATION We have studied how to model and simplify real life problems into graphs In this course topic, we will further discuss how to represent a graph in a computer program and implements some fundamental graph algorithms Adjacency Matrix representation Adjacency List representation DFS & BFS Traversal Dijkstra’s shortest path (later) Minimum Spanning Tree (later) In term of programming, a vertex usually carries extra information, thus it is sometimes called a node

G RAPH R EPRESENTATION A DJACENCY M ATRIX An adjacency matrix representation of a graph is a n-by-n matrix of Boolean values, with the entry in row v and column w defined to be 1 if there is an edge connecting vertex v and vertex w in the graph, and 0 otherwise. Example:

When the graph is directed, row v column w is defined to be 1 if there is an edge from v to w Example: G RAPH R EPRESENTATION A DJACENCY M ATRIX

If we need to label the edges, we can use integer values instead of Booleans Example: relationship graph (1)Ann (3)Tom (2)Bob (4)Lea (6)Noah (5)Jim (6)close friend (1)spouse (4)co-worker (3)lover (2)buddy (5)family (7)acquaintance 1 Ann 2 Bob 3 Tom 4 Lea 5 Jim 6 Noah 1 spouse 2 buddy 3 lover 4 co-worker 5 family 6 close friend 7 acquaintance verticesedges matrix

G RAPH R EPRESENTATION A DJACENCY L IST Adjacency matrix representation is easy to implement with arrays, however, when the graph is sparse (has few edges), it wastes a lot of memory space. Adjacency list tries to answer this problem. Edges’ information are stored in an array of linked list.

G RAPH R EPRESENTATION A DJACENCY L IST :: E XAMPLE

We can add vertex’s and edge’s information to the linked list’s node (1)Ann (3)Tom (2)Bob (4)Lea (6)Noah (5)Jim (6)close friend (1)spouse (4)co-worker (3)lover (2)buddy (5)family (7)acquaintance G RAPH R EPRESENTATION A DJACENCY L IST :: E XAMPLE 1 Ann 2 Bob 3 Tom 4 Lea 5 Jim 6 Noah 2spouse6 acquaintance 2buddy4lover5family2 co-worker6close-friend

DFS A LGORITHM We have discussed DFS traversal in a tree or graph. This traversal method can be easily implemented recursively: To visit a vertex, we mark it as having been visited, then (recursively) visit all the vertices that are adjacent to it and that have not yet been marked To mark which vertex has been visited, we can use a Boolean array, initially set to 0

DFS A LGORITHM DFS(G) initialize isVisited[0..n] to false for each unvisited vertex v of G DFS_RECURSIVE(v) DFS_RECURSIVE(x) isVisited[x] = true process(x) for each unvisited vertex v adjacent to x DFS_RECURSIVE(v) DFS(G) initialize isVisited[0..n] to false for each unvisited vertex v of G DFS_RECURSIVE(v) DFS_RECURSIVE(x) isVisited[x] = true process(x) for each unvisited vertex v adjacent to x DFS_RECURSIVE(v) Simple DFS Algorithm

DFS A LGORITHM Sometimes we need to know the order of vertex visited Use an array of n integer to store the order of vertex visited, instead of array of Boolean isVisited. The array is initially set to 0 (unvisited). Sometimes we also need to store the traversal tree Use an array of n integer to store the parent’s index of each vertex (remember, each vertex of a tree has exactly one parent, except the root). The array is initially set to 0. The vertex (or vertices) which parent remains 0 is the root of the traversal tree (or forest if the graph is disconnected).

DFS A LGORITHM // global variable ctr = 1 DFS(G) initialize ord[0..n] to 0 initialize parent[0..n] to 0 for each unvisited vertex v of G DFS_RECURSIVE(v) DFS_RECURSIVE(x) ord[x] = ctr ctr = ctr+1 process(x) for each unvisited vertex v adjacent to x parent[v] = x DFS_RECURSIVE(v) // global variable ctr = 1 DFS(G) initialize ord[0..n] to 0 initialize parent[0..n] to 0 for each unvisited vertex v of G DFS_RECURSIVE(v) DFS_RECURSIVE(x) ord[x] = ctr ctr = ctr+1 process(x) for each unvisited vertex v adjacent to x parent[v] = x DFS_RECURSIVE(v) DFS Algorithm with ord and parent array

DFS T REE D E B F G C I A H D E B F G C I A H D EB F G C I A H DFS Tree Recall…

DFS T REE P ROPERTIES During DFS traversal on vertex v, we know a vertex u adjacent to v is already visited iff ord[u] is not 0. In fact, we can further examine : If ord[u] < ord[v], then v is u ’s ancestor, because v is visited before u If ord[u] > ord[v], then v is u ’s descendant, because v is visited after u If parent[u] is v, then v is u ’s ancestor and also a direct parent of u Based on these observation, we can “upgrade” our DFS Tree to show more information

DFS T REE D E B F G C I A H D E B F G C I A H D E B F G C I A H DFS Tree A B A H F E F I B C G G BF = parent = down edge DOWN = back edge BACK

DFS T REE D E B F G C I A H D E B F G C I A H ABCDEFGHI parent 0FBEFICAH ord D E B F G C I A H DFS Tree A B A H F E F I B C G G BF #back edge = #down edge = #chord = #edges that form circuits #back edge = #down edge = #chord = #edges that form circuits

E XERCISE Draw the DFS traversal tree and fill the ord & parent array for this graph ! D E B F G C I A H J K

DFS A LGORITHM Simple to implement using recursive The base of many useful algorithm, such as Counting component(s) in a graph Connectivity Flood-fill Topological sort Finding bridge Finding articulation point Etc.

DFS A LGORITHM C OUNTING COMPONENT ( S ) CountComponent(G) component = 0 for each unvisited vertex v of G component = component + 1 DFS_RECURSIVE(v) return component CountComponent(G) component = 0 for each unvisited vertex v of G component = component + 1 DFS_RECURSIVE(v) return component Same as counting how many trees in DFS forest

DFS A LGORITHM C ONNECTIVITY isConnected(G) component = 0 for each unvisited vertex v of G component = component + 1 DFS_RECURSIVE(v) return (component == 1) isConnected(G) component = 0 for each unvisited vertex v of G component = component + 1 DFS_RECURSIVE(v) return (component == 1) Returns true if graph G is connected, returns false otherwise If #component > 1, then graph must be disconnected

“Flooding” a component that contains vertex v Same as performing DFS on a single tree only Sometimes we’re interested to know which vertex (or vertices) are flooded, in such case, we can return the ord array DFS A LGORITHM F LOOD F ILL FloodFill(v) DFS_RECURSIVE(v) return ord FloodFill(v) DFS_RECURSIVE(v) return ord

P ROBLEM SCHEDULING TASKS IN THE MORNING Wear socks Wear shoes Take a bath Wear clothes Eat breakfast Cook breakfast Get inside a car Drive to campus Get schoolbag Brew a cup of coffee Drink coffee

T OPOLOGICAL S ORTING Topological sort of a directed graph is a linear ordering of its vertices such that for every directed edge ( u  v ), vertex u comes before vertex v in the ordering Only possible iff the graph does not have any directed cycle D E C D E C OK Not OK

P ROBLEM SCHEDULING TASKS IN THE MORNING Wear socks Wear shoes Take a bath Wear clothes Eat breakfast Cook breakfast Get inside a car Drive to campus Get schoolbag Brew a cup of coffee Drink coffee in=1 in=2out=3 out=8 in=4out=7 Eat breakfast Drive to campus Drink coffee Cook breakfast in=9out=10 in=5out=6 Take a bath in=15out=20 Wear socks in=11out=14 Wear clothes in=16out=19 Get inside a car in=17out=18 Wear shoes in=12out=13 Get schoolbag in=21out=22 Descending sort by “out” : Get schoolbag(22) – Take a bath(20) – Wear clothes(19) – Get inside a car(18) – Wear socks (14) – Wear shoes (13) – Cook Breakfast(10) – Brew a cup of coffee(8) – Eat Breakfast(7) – Drive to campus(6) – Drink coffee(3)

Descending sort by “out” : Get schoolbag(22) – Take a bath(20) – Wear clothes(19) – Get inside a car(18) – Wear socks (14) – Wear shoes (13) – Cook Breakfast(10) – Brew a cup of coffee(8) – Eat Breakfast(7) – Drive to campus(6) – Drink coffee(3) P ROBLEM SCHEDULING TASKS IN THE MORNING Wear socks Wear shoes Take a bath Wear clothes Eat breakfast Cook breakfast Get inside a car Drive to campus Get schoolbag Brew a cup of coffee Drink coffee

T OPOLOGICAL S ORTING A LGORITHM // global variable ctr = 1 // global stack S = empty stack DFS(G) initialize ord_in[0..n] to 0 initialize ord_out[0..n] to 0 for each unvisited vertex v of G DFS_RECURSIVE(v) return S DFS_RECURSIVE(x) ord_in[x] = ctr ctr = ctr+1 process(x) for each vertex v adjacent to x if ord_in[v] != 0 AND ord_out[v] == 0 stop, graph is not DAG else if ord_in[v] == 0//unvisited DFS_RECURSIVE(v) S.push(x) ord_out[x] = ctr ctr = ctr + 1 // global variable ctr = 1 // global stack S = empty stack DFS(G) initialize ord_in[0..n] to 0 initialize ord_out[0..n] to 0 for each unvisited vertex v of G DFS_RECURSIVE(v) return S DFS_RECURSIVE(x) ord_in[x] = ctr ctr = ctr+1 process(x) for each vertex v adjacent to x if ord_in[v] != 0 AND ord_out[v] == 0 stop, graph is not DAG else if ord_in[v] == 0//unvisited DFS_RECURSIVE(v) S.push(x) ord_out[x] = ctr ctr = ctr + 1

E XERCISE Find the topological order for these vertices ! D E B F G C I A H J K

BFS A LGORITHM Suppose that we want to find a shortest path between two specific vertices in a graph (a path connecting the vertices with the property that no other path connecting those vertices has fewer edges) The classical method for accomplishing this task is breadth-first search Can be easily implemented with a queue

BFS T REE P ROPERTY Recall… D E B F G C I A H D E B F G C I A H D E B F GC I A H BFS Tree For any vertex v in the BFS tree rooted at r, the tree path from r to v corresponds to a shortest path from r to v in the corresponding graph

BFS A LGORITHM BFS(G) Q = empty queue initialize isVisited[0..n] to false for each unvisited vertex v of G Q.enqueue(v) isVisited[v] = true while(Q is not empty) x = Q.dequeue() process(x) for each unvisited vertex u adjacent to x isVisited[v] = true Q.enqueue(u) BFS(G) Q = empty queue initialize isVisited[0..n] to false for each unvisited vertex v of G Q.enqueue(v) isVisited[v] = true while(Q is not empty) x = Q.dequeue() process(x) for each unvisited vertex u adjacent to x isVisited[v] = true Q.enqueue(u) Simple BFS Algorithm

BFS A LGORITHM To find the shortest path from any node to the root, we need to store the BFS traversal tree Adds array parent to store the parent of each node Similar to DFS algorithm, we might want to know the order the vertices visited Use array ord to store the order each vertex visited

BFS A LGORITHM BFS(G) ctr = 1 Q = empty queue initialize ord[0..n] to 0 initialize parent[0..n] to 0 for each unvisited vertex v of G Q.enqueue(v) ord[v] = ctr ctr = ctr+1 while(Q is not empty) x = Q.dequeue() process(x) for each unvisited vertex u adjacent to x parent[u] = x ord[x] = ctr ctr = ctr+1 Q.enqueue(u) BFS(G) ctr = 1 Q = empty queue initialize ord[0..n] to 0 initialize parent[0..n] to 0 for each unvisited vertex v of G Q.enqueue(v) ord[v] = ctr ctr = ctr+1 while(Q is not empty) x = Q.dequeue() process(x) for each unvisited vertex u adjacent to x parent[u] = x ord[x] = ctr ctr = ctr+1 Q.enqueue(u) BFS Algorithm with parent and ord arrays

BFS A LGORITHM Same as DFS, BFS algorithm also able to solve basic connectivity problems, such as: flood fill, counting component, spanning tree. Note: topological sort is not a connectivity problem The solutions of these problems only depends of the ability to examine every vertex of the graph, not the order we visit the vertices

DFS V. S. BFS D E B F G C I A H D EB F G C I A H DFS Tree D E B F GC I A H BFS Tree Consider our previous example DFS tree has several interesting properties such as down/back edge, which is useful to solve some important problems (i.e., finding bridge and articulation point) However, DFS tree is usually deep. Computer program usually has a limitation on how much recursive calls possible, so for large graph, recursive DFS might not feasible. In such case, we use BFS (or iterative version of DFS)

DFS V. S. BFS EXAMPLE Tree height = #vertices = n 2 Tree height = 2n-1

T IME C OMPLEXITY Graph traversal is meant to visit each vertex exactly once, thus there might be some edges remain unvisited  seems like O(#vertices) In practice we still need to visit every edges (including the chords) to check whether the vertex on its other end is already visited So the time complexity for traversing a graph with V vertices and E edges is O(V+E) for adjacency list representation O(V 2 ) for adjacency matrix representation