Graph Traversals Depth-First Traversals. Algorithms. Example.

Slides:



Advertisements
Similar presentations
CSE 390B: Graph Algorithms Based on CSE 373 slides by Jessica Miller, Ruth Anderson 1.
Advertisements

CS 206 Introduction to Computer Science II 03 / 27 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 11 / 11 / Veterans Day Instructor: Michael Eckmann.
Graph Traversals Introduction Breadth-First Traversal. The Algorithm.
Topological Sort Introduction. Definition of Topological Sort.
Testing for Connectedness and Cycles
1 Testing for Connectedness and Cycles Connectedness of Undirected Graphs Implementation of Connectedness detection Algorithm for Undirected Graphs. Implementation.
Graph Traversals Depth-First Traversal. The Algorithm.
CS 206 Introduction to Computer Science II 11 / 03 / 2008 Instructor: Michael Eckmann.
©Brooks/Cole, 2003 Chapter 12 Abstract Data Type.
Graph Traversals Depth-First Traversals. –Algorithms. –Example. –Implementation. Breadth-First Traversal. –The Algorithm. –Example. –Implementation. Review.
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.
Graph Traversals General Traversal Algorithm Depth-First Traversals. –Algorithms. –Example. –Implementation. Breadth-First Traversal. –The Algorithm. –Example.
CS 206 Introduction to Computer Science II 11 / 09 / 2009 Instructor: Michael Eckmann.
Graphs & Graph Algorithms Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
1 Topological Sort Introduction. Definition of Topological Sort. Topological Sort is Not Unique. Topological Sort Algorithms. An Example. Implementation.
CS 206 Introduction to Computer Science II 03 / 30 / 2009 Instructor: Michael Eckmann.
Testing for Connectedness and Cycles Connectedness of an Undirected Graph Implementation of Connectedness detection Algorithm. Implementation of Strong.
Topological Sort Introduction. Definition of Topological Sort. Topological Sort is Not Unique. Topological Sort Algorithm. An Example. Implementation.
Chapter 9 – Graphs A graph G=(V,E) – vertices and edges
All leaves are on the bottom level. All internal nodes (except perhaps the root node) have at least ceil(m / 2) (nonempty) children. The root node can.
U n i v e r s i t y o f H a i l ICS 202  2011 spring  Data Structures and Algorithms  1.
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,
Introduction to Graphs. Introduction Graphs are a generalization of trees –Nodes or verticies –Edges or arcs Two kinds of graphs –Directed –Undirected.
Graphs – Part II CS 367 – Introduction to Data Structures.
COSC 2007 Data Structures II
DIRECTED ACYCLIC GRAPHS AND TOPOLOGICAL SORT CS16: Introduction to Data Structures & Algorithms Tuesday, March 10,
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
Minimum Spanning Tree What is a Minimum Spanning Tree.
1 Trees General Trees  Nonrecursive definition: a tree consists of a set of nodes and a set of directed edges that connect pairs of nodes.
CSE 421 Algorithms Richard Anderson Autumn 2015 Lecture 5.
Graph Theory Def: A graph is a set of vertices and edges G={V,E} Ex. V = {a,b,c,d,e} E = {ab,bd,ad,ed,ce,cd} Note: above is a purely mathematical definition.
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.
© 2006 Pearson Addison-Wesley. All rights reserved14 B-1 Chapter 14 (continued) Graphs.
Breadth-First Search (BFS)
Graphs A New Data Structure
Topological Sorting.
Minimum Spanning Tree What is a Minimum Spanning Tree.
CS212: Data Structures and Algorithms
Unit 10 Graphs (1) King Fahd University of Petroleum & Minerals
CSE 373 Topological Sort Graph Traversals
Fundamentals, Terminology, Traversal, Algorithms
CSE373: Data Structures & Algorithms Lecture 13: Topological Sort / Graph Traversals Kevin Quinn Fall 2015.
Csc 2720 Instructor: Zhuojun Duan
Depth-First Search.
CS202 - Fundamental Structures of Computer Science II
More Graph Algorithms.
Graph Traversals Depth-First Traversals. Algorithms. Example.
Graphs Graph transversals.
Testing for Connectedness and Cycles
Topological Sort Introduction. Definition of Topological Sort.
"Learning how to learn is life's most important skill. " - Tony Buzan
Search Related Algorithms
Topological Sort CSE 373 Data Structures Lecture 19.
Chapter 22: Elementary Graph Algorithms
Chapter 11 Graphs.
Graph Traversals Depth-First Traversals. Algorithms. Example.
Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013
Richard Anderson Autumn 2016 Lecture 5
Graph Implementation.
Topological Sort Introduction. Definition of Topological Sort.
Chapter 14 Graphs © 2011 Pearson Addison-Wesley. All rights reserved.
Topological Sort Introduction. Definition of Topological Sort.
Richard Anderson Winter 2019 Lecture 6
Topological Sort Introduction. Definition of Topological Sort.
Richard Anderson Autumn 2015 Lecture 6
Graph Traversals Depth-First Traversals. Algorithms. Example.
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 .
Presentation transcript:

Graph Traversals Depth-First Traversals. Algorithms. Example. Implementation. Breadth-First Traversal. The Algorithm. Topological Sort Review Questions.

Depth-First Traversal Algorithm In this method, After visiting a vertex v, which is adjacent to w1, w2, w3, ...; Next we visit one of v's adjacent vertices, say w1. Next, we visit all vertices adjacent to w1 before coming back to w2, etc. Must keep track of vertices already visited to avoid cycles. The method can be implemented using recursion or iteration. The iterative preorder depth-first algorithm is: 1 push the starting vertex onto the stack 2 while(stack is not empty){ 3 pop a vertex off the stack, call it v 4 if v is not already visited, visit it push vertices adjacent to v, not visited, onto the stack } Note: Adjacent vertices can be pushed in any order; but to obtain a unique traversal, we will push them in reverse alphabetical order.

Example Demonstrates depth-first traversal using an explicit stack. Order of Traversal Stack A B C F E G D H I

Recursive preorder Depth-First Traversal Implementation dfsPreorder(v){ visit v; for(each neighbour w of v) if(w has not been visited) dfsPreorder(w); } The following is the code for the recursive preorderDepthFirstTraversal method of the AbstractGraph class: public void preorderDepthFirstTraversal(Visitor visitor, Vertex start) { boolean visited[] = new boolean[numberOfVertices]; for(int v = 0; v < numberOfVertices; v++) visited[v] = false; preorderDepthFirstTraversal(visitor, start, visited); }

Recursive preorder Depth-First Traversal Implementation (cont’d) private void preorderDepthFirstTraversal(Visitor visitor, Vertex v, boolean[] visited) { if(visitor.isDone()) return; visitor.visit(v); visited[getIndex(v)] = true; Iterator p = v.getSuccessors(); while(p.hasNext()) { Vertex to = (Vertex) p.next(); if(! visited[getIndex(to)]) preorderDepthFirstTraversal(visitor, to, visited); }

Recursive preorder Depth-First Traversal Implementation (cont’d) At each stage, a set of unvisited adjacent vertices of the current vertex is generated.

Recursive postorder Depth-First Traversal Implementation dfsPostorder(v){ mark v; for(each neighbour w of v) if(w is not marked) dfsPostorder(w); visit v; } The following is the code for the recursive postorderDepthFirstTraversal method of the AbstractGraph class: public void postorderDepthFirstTraversal(Visitor visitor, Vertex start) { boolean visited[] = new boolean[numberOfVertices]; for(int v = 0; v < numberOfVertices; v++) visited[v] = false; postorderDepthFirstTraversal(visitor, start, visited); }

Recursive postorder Depth-First Traversal Implementation (cont’d) private void postorderDepthFirstTraversal( Visitor visitor, Vertex v, boolean[] visited) { if(visitor.isDone()) return; // mark v visited[getIndex(v)] = true; Iterator p = v.getSuccessors(); while(p.hasNext()){ Vertex to = (Vertex) p.next(); if(! visited[getIndex(to)]) postorderDepthFirstTraversal(visitor, to, visited); } // visit v visitor.visit(v);

Recursive postorder Depth-First Traversal Implementation (cont’d) At each stage, a set of unmarked adjacent vertices of the current vertex is generated.

Breadth-First Traversal Algorithm In this method, After visiting a vertex v, we must visit all its adjacent vertices w1, w2, w3, ..., before going down next level to visit vertices adjacent to w1 etc. The method can be implemented using a queue. A boolean array is used to ensure that a vertex is enqueued only once. 1 enqueue the starting vertex 2 while(queue is not empty){ 3 dequeue a vertex v from the queue; 4 visit v. enqueue vertices adjacent to v that were never enqueued; } Note: Adjacent vertices can be enqueued in any order; but to obtain a unique traversal, we will enqueue them in alphabetical order.

Example Demonstrating breadth-first traversal using a queue. Order of Traversal Queue rear A B D E C G F H I Queue front

Breadth-First Traversal Implementation public void breadthFirstTraversal(Visitor visitor, Vertex start){ boolean enqueued[] = new boolean[numberOfVertices]; for(int i = 0; i < numberOfVertices; i++) enqueued[i] = false; Queue queue = new QueueAsLinkedList(); enqueued[getIndex(start)] = true; queue.enqueue(start); while(!queue.isEmpty() && !visitor.isDone()) { Vertex v = (Vertex) queue.dequeue(); visitor.visit(v); Iterator it = v.getSuccessors(); while(it.hasNext()) { Vertex to = (Vertex) it.next(); int index = getIndex(to); if(!enqueued[index]) { enqueued[index] = true; queue.enqueue(to); } //enqueue the starting vertex //dequeue a vertex v from the queue // visit v //enqueue vertices adjacent to v that were never enqueued

Review Questions 1. Considera depth-first traversal of the undirected graph GA shown above, starting from vertex a. List the order in which the nodes are visited in a preorder traversal. List the order in which the nodes are visited in a postorder traversal 2. Repeat exercise 1 above for a depth-first traversal starting from vertex d. 3. List the order in which the nodes of the undirected graph GA shown above are visited by a breadth first traversal that starts from vertex a. Repeat this exercise for a breadth-first traversal starting from vertex d. 4. Repeat Exercises 1 and 3 for the directed graph GB.

Topological Sort Introduction. Definition of Topological Sort. Topological Sort is Not Unique. Topological Sort Algorithm. An Example. Implementation. Review Questions. 14

Introduction There are many problems involving a set of tasks in which some of the tasks must be done before others. For example, consider the problem of taking a course only after taking its prerequisites. Is there any systematic way of linearly arranging the courses in the order that they should be taken? Yes! - Topological sort. 15

Definition of Topological Sort Topological sort is a method of arranging the vertices in a directed acyclic graph (DAG), as a sequence, such that no vertex appear in the sequence before its predecessor. The graph in (a) can be topologically sorted as in (b) (a) (b) 16

Topological Sort is not unique The following are all topological sort of the graph below: s1 = {a, b, c, d, e, f, g, h, i} s2 = {a, c, b, f, e, d, h, g, i} s3 = {a, b, d, c, e, g, f, h, i} s4 = {a, c, f, b, e, h, d, g, i} etc. 17

Topological Sort Algorithm One way to find a topological sort is to consider in-degrees of the vertices. The first vertex must have in-degree zero -- every DAG must have at least one vertex with in-degree zero. The Topological sort algorithm is: int topologicalOrderTraversal( ){ int numVisitedVertices = 0; while(there are more vertices to be visited){ if(there is no vertex with in-degree 0) break; else{ select a vertex v that has in-degree 0; visit v; numVisitedVertices++; delete v and all its emanating edges; } return numVisitedVertices; 18

Topological Sort Example Demonstrating Topological Sort. A F B G C H D I E J 1 2 3 D G A B F H J E I C 19

Implementation of Topological Sort The algorithm is implemented as a traversal method that visits the vertices in a topological sort order. An array of length |V| is used to record the in-degrees of the vertices. Hence no need to remove vertices or edges. A priority queue is used to keep track of vertices with in-degree zero that are not yet visited. public int topologicalOrderTraversal(Visitor visitor){ int numVerticesVisited = 0; int[] inDegree = new int[numberOfVertices]; for(int i = 0; i < numberOfVertices; i++) inDegree[i] = 0; Iterator p = getEdges(); while (p.hasNext()) { Edge edge = (Edge) p.next(); Vertex to = edge.getToVertex(); inDegree[getIndex(to)]++; } 20

Implementation of Topological Sort BinaryHeap queue = new BinaryHeap(numberOfVertices); p = getVertices(); while(p.hasNext()){ Vertex v = (Vertex)p.next(); if(inDegree[getIndex(v)] == 0) queue.enqueue(v); } while(!queue.isEmpty() && !visitor.isDone()){ Vertex v = (Vertex)queue.dequeueMin(); visitor.visit(v); numVerticesVisited++; p = v.getSuccessors(); while (p.hasNext()){ Vertex to = (Vertex) p.next(); if(--inDegree[getIndex(to)] == 0) queue.enqueue(to); return numVerticesVisited; 21

Review Questions 1. List the order in which the nodes of the directed graph GB are visited by topological order traversal that starts from vertex a. 2. What kind of DAG has a unique topological sort? 3. Generate a directed graph using the required courses for your major. Now apply topological sort on the directed graph you obtained. 22