Podcast Ch24d Title: Depth First Search and Acyclic Graphs

Slides:



Advertisements
Similar presentations
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.
Advertisements

Elementary Graph Algorithms Depth-first search.Topological Sort. Strongly connected components. Chapter 22 CLRS.
Algorithms and Data Structures
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 24 Graphs.
Algoritma Traversal Graph. Graph Traversal Algorithms In general, graphs do not have a vertex, like a root, that initiates unique paths to each of the.
Spring 2010CS 2251 Graphs Chapter 10. Spring 2010CS 2252 Chapter Objectives To become familiar with graph terminology and the different types of graphs.
COMP171 Depth-First Search.
Lecture 15: Depth First Search Shang-Hua Teng. Graphs G= (V,E) B E C F D A B E C F D A Directed Graph (digraph) –Degree: in/out Undirected Graph –Adjacency.
Depth-first search COMP171 Fall Graph / Slide 2 Depth-First Search (DFS) * DFS is another popular graph search strategy n Idea is similar to pre-order.
Depth-First Search Lecture 24 COMP171 Fall Graph / Slide 2 Depth-First Search (DFS) * DFS is another popular graph search strategy n Idea is similar.
Depth-First Search Idea: Keep going forward as long as there are unseen nodes to be visited. Backtrack when stuck. v G G G G is completely traversed.
1 Graphs & Characteristics Graph Representations A Representation in C++ (Ford & Topp) Searching (DFS & BFS) Connected Components Graph G and Its Transpose.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 25 Graph.
Elementary Graph Algorithms CLRS Chapter 22. Graph A graph is a structure that consists of a set of vertices and a set of edges between pairs of vertices.
Data Structures & Algorithms Graphs. Graph Terminology A graph consists of a set of vertices V, along with a set of edges E that connect pairs of vertices.
CSC 413/513: Intro to Algorithms Graph Algorithms DFS.
Analysis of Algorithms CS 477/677 Instructor: Monica Nicolescu Lecture 20.
Graphs A graphs is an abstract representation of a set of objects, called vertices or nodes, where some pairs of the objects are connected by links, called.
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.
7. Graph Traversal Describe and compare depth-first and breadth-first graph searching, and look at the creation of spanning trees Contest Algorithms: 7.
CSC317 1 At the same time: Breadth-first search tree: If node v is discovered after u then edge uv is added to the tree. We say that u is a predecessor.
Code: BCA302 Data Structures with C Prof. (Dr.) Monalisa Banerjee By.
Representing Graphs Depth First Search Breadth First Search Graph Searching Algorithms.
Review Graph Directed Graph Undirected Graph Sub-Graph Spanning Sub-Graph Degree of a Vertex Weighted Graph Elementary and Simple Path Link List Representation.
Podcast Ch24c Title: Breadth First Search
CSE 373 Data Structures and Algorithms
Graphs Breadth First Search & Depth First Search
Podcast Ch17b Title: Iterative Tree Traversal
Chapter 22 Elementary Graph Algorithms
Tracing An Algorithm for Strongly Connected Components that uses Depth First Search Graph obtained from Text, page a-al: Geetika Tewari.
Podcast Ch26a Title: Representing Graphs
CSE 2331/5331 Topic 9: Basic Graph Alg.
Depth-First Search Depth-first search is a strategy for exploring a graph Explore “deeper” in the graph whenever possible Edges are explored out of the.
Podcast Ch17a Title: Expression Trees
Graphs Breadth First Search & Depth First Search
Graph Algorithms Using Depth First Search
Data Structures and Algorithms for Information Processing
Spanning Trees Longin Jan Latecki Temple University based on slides by
Data Structures for Java William H. Ford William R. Topp
Graphs Graph transversals.
Graphs A graph G = (V, E) V = set of vertices, E = set of edges
Finding Shortest Paths
Search Related Algorithms
Graph Representation (23.1/22.1)
Podcast Ch25d Title: Minimum Path Algorithm
Podcast Ch18b Title: STree Class
Graphs Part 2 Adjacency Matrix
Depth-First Search Graph Traversals Depth-First Search DFS.
Podcast Ch24b Title: Graphs and Digraphs
Data Structures & Algorithms
COMP171 Depth-First Search.
Podcast Ch18c Title: BST delete operation
Podcast Ch25c Title: Shortest Path Algorithm
Graph Algorithms "A charlatan makes obscure what is clear; a thinker makes clear what is obscure. " - Hugh Kingsmill CLRS, Sections 22.2 – 22.4.
Depth-First Search CSE 2011 Winter April 2019.
Podcast Ch22b Title: Inserting into a Heap
Graph Implementation.
Depth-First Search CSE 2011 Winter April 2019.
Podcast Ch18a Title: Overview of Binary Search Trees
GRAPHS G=<V,E> Adjacent vertices Undirected graph
Chapter 16 1 – Graphs Graph Categories Strong Components
Podcast Ch18d Title: Binary Search Tree Iterator
Podcast Ch21d Title: Hash Class Iterators
Spanning Trees Longin Jan Latecki Temple University based on slides by
Podcast Ch26b Title: Digraph Class Implementation
Podcast Ch27b Title: AVLTree implementation
Applications of BFS CSE 2011 Winter /17/2019 7:03 AM.
Elementary Graph Algorithms
CSC 325: Algorithms Graph Algorithms David Luebke /24/2019.
Podcast Ch24b Title: Strongly Connected Components
Presentation transcript:

Podcast Ch24d Title: Depth First Search and Acyclic Graphs Description: Depth-first visit; dfsVisit() method; dfs() method; acyclic graphs; Program 24.2 Participants: Barry Kurtz (instructor); John Helfert and Tobie Williams (students) Textbook: Data Structures for Java; William H. Ford and William R. Topp

Depth-First Visit The depth-first visit algorithm is modeled after the recursive postorder scan of a binary tree. In the tree, a node is visited only after visits are made to all of the nodes in its subtree. In the graph, a node is visited only after visiting all of the nodes in paths that emanate from the node.

Depth-First Visit (continued) Color all vertices WHITE. A vertex is colored GRAY when it is first contacted in a recursive descent. Only when the vertex is actually visited does it become BLACK. Begin at a starting vertex and search down paths of neighbors until reaching a vertex that has no neighbors or only neighbors that are BLACK. At this point, a visit occurs at the "terminal" vertex and it becomes BLACK.

Depth-First Visit (continued) Backtrack to the previous recursive step and look for another adjacent vertex and launch a scan down its paths. There is no ordering among vertices in an adjacency list, so the paths and hence the order of visits to vertices can vary.

Depth-First Visit (continued) Discover A (color GRAY) Discover B (color GRAY) Discover D (color GRAY) Discover E (color GRAY, then BLACK) Backtrack D (color BLACK) Backtrack B (color BLACK) Backtrack A (A remains GRAY) Discover C (color BLACK) Backtrack A (color BLACK). Visit complete.

Depth-First Visit (continued) The depth‑first visit is a recursive algorithm that distinguishes the discovery and finishing time (when a vertex becomes BLACK) of a vertex. The depth‑first visit returns a list of the vertices found in the reverse order of their finishing times.

Depth-First Visit (continued) An edge that connects a vertex to a neighbor that has color GRAY is called a back edge. A depth-first visit has a cycle if and only if it has a back edge.

dfsVisit() // depth-first visit assuming a WHITE starting // vertex; dfsList contains the visited vertices // in reverse order of finishing time; when // checkForCycle is true, throws // IllegalPathStateException if itmdetects a cycle public static <T> void dfsVisit(DiGraph<T> g, T sVertex,LinkedList<T> dfsList, boolean checkForCycle) { T neighborVertex; Set<T> edgeSet; // iterator to scan the adjacency set of a vertex Iterator<T> edgeIter; VertexColor color; if (!g.containsVertex(sVertex)) throw new IllegalArgumentException( "dfsVisit(): vertex not in the graph");

dfsVisit() (continued) // color vertex GRAY to note its discovery g.setColor(sVertex, VertexColor.GRAY); edgeSet = g.getNeighbors(sVertex); // sequence through the adjacency set and look // for vertices that are not yet discovered // (colored WHITE); recursively call dfsVisit() // for each such vertex; if a vertex in the // adjacency list is GRAY, the vertex was // discovered during a previous call and there // is a cycle that begins and // ends at the vertex; if checkForCycle is true, // throw an exception edgeIter = edgeSet.iterator();

dfsVisit() (concluded) while (edgeIter.hasNext()){ neighborVertex = edgeIter.next(); color = g.getColor(neighborVertex); if (color == VertexColor.WHITE) dfsVisit(g, neighborVertex, dfsList, checkForCycle); else if (color == VertexColor.GRAY && checkForCycle) throw new IllegalPathStateException( "dfsVisit(): graph has a cycle"); } // finished with vertex sVertex; make it BLACK // and add it to the front of dfsList g.setColor(sVertex, VertexColor.BLACK); dfsList.addFirst(sVertex);

Depth-First Visit Example LinkedList<String> finishOrder = new LinkedList<String>(); g.colorWhite(); DiGraphs.dfsVisit(g, "B", finishOrder, false); Output: finishOrder: [B, D, E, F, C]

Depth-First Visit Example (concluded) finishOrder = new LinkedList<String>(); g.colorWhite(); Try { DiGraphs.dfsVisit(g, "E", finishOrder, true); System.out.println("finishOrder: " + finishOrder); } catch (IllegalPathStateException ipse) { System.out.println(ipse.getMessage()); Output: dfsVisit(): cycle involving vertices D and E

Student Question List the vertices in the reverse order of their visit (finish) time for a depth-first visit (dfsVisit) that starts at vertex A and first accesses C as its neighbor. Repeat the process, but produce a different list by assuming that the search first accesses neighbor F. List 1: __________________________________________________ List 2: __________________________________________________

Student Question List the vertices in the reverse order of their visit (finish) time for a depth-first visit that starts at vertex E. List: ______________________________________________ A depth-first search of a graph using a series of depth-first visits to scan the vertices. The algorithm selects from the set of unvisited vertices to launch each depth-first visit. Give the complete list of vertices in the reverse order of their finish time for a depth-first search assuming that the algorithm selects the next unvisited vertex for the depth-first visits in the order "A", "B", ...., "F". List: _________________________________________________

Depth-First Search Algorithm Depth‑first search begins with all WHITE vertices and performs depth‑first visits until all vertices of the graph are BLACK. The algorithm returns a list of all vertices in the graph in the reverse order of their finishing times.

dfs() // depth-first search; dfsList contains all // the graph vertices in the reverse order // of their finishing times public static <T> void dfs(DiGraph<T> g, LinkedList<T> dfsList) { Iterator<T> graphIter; T vertex = null; // clear dfsList dfsList.clear(); // initialize all vertices to WHITE g.colorWhite();

dfs() (concluded) // call dfsVisit() for each WHITE vertex graphIter = g.vertexSet().iterator(); while (graphIter.hasNext()) { vertex = graphIter.next(); if (g.getColor(vertex) == VertexColor.WHITE) dfsVisit(g, vertex, dfsList, false); }

Running Time for Depth-First Search An argument similar to that for the breadth-first search shows that that the running time for dfs() is O(V+E), where V is the number of vertices in the graph and E is the number of edges.

Depth-First Search Example dfsVisit() starting at E followed by dfsVisit() starting at A dfsList: [A, B, C, E, F, G, D]

Student Question List the vertices in reverse order of finish time for a depth-first visit starting at vertex A. dfsList: [ ______________________________________________ ] depth-first visit starting at vertex E. What is the complexity of the depth-first search when a graph with V vertices and E edges is stored using the adjacency list representation? O(________________)

Acyclic Graphs To check for a cycle anywhere in a graph, traverse all of the vertices by using multiple calls to dfsVisit(). This is essentially the dfs() algorithm where the focus is on identifying cycles and not obtaining a list of visited vertices. This approach relies on the fact that any cycle must be included within one of the calls to dfsVisit(). The method, with checkForCycle set to true, identifies the cycle.

acyclic() // determine if the graph is acyclic public static <T> boolean acyclic(DiGraph<T> g) { // use for calls to dfsVisit() LinkedList<T> dfsList = new LinkedList<T>(); Iterator<T> graphIter; T vertex = null; // initialize all vertices to WHITE g.colorWhite(); // call dfsVisit() for each WHITE vertex; catch // an IllegalPathStateException in a call to // dfsVisit() try { // call dfsVisit() for each WHITE vertex graphIter = g.vertexSet().iterator();

acyclic() (concluded) while (graphIter.hasNext()) { vertex = graphIter.next(); if (g.getColor(vertex) == VertexColor.WHITE) dfsVisit(g,vertex, dfsList, true); } catch (IllegalPathStateException iae) return false; return true;

Program 24.2 import java.io.FileNotFoundException; import ds.util.DiGraph; import ds.util.DiGraphs; public class Program24_2 { public static void main(String[] args) throws FileNotFoundException { DiGraph<String> g = DiGraph.readGraph("cycle.dat"); // determine if the graph is acyclic if (DiGraphs.acyclic(g)) System.out.println("Graph is acyclic"); else System.out.println("Graph is not acyclic");

Program 24.2 (concluded) // add edge (E,B) to create a cycle System.out.print(" Adding edge (E,B): "); g.addEdge("E", "B", 1); // retest the graph to see if it is acyclic if (DiGraphs.acyclic(g)) System.out.println("New graph is acyclic"); else System.out.println("New graph is not acyclic"); } Run: Graph is acyclic Adding edge (E,B): New graph is not acyclic

Student Question During a recursive depth-first visit of a digraph, what is back edge? What is the relation between a back edge and an acyclic graph?