Data Structures for Java William H Ford William

  • Slides: 71
Download presentation
Data Structures for Java William H. Ford William R. Topp Chapter 24 Graphs and

Data Structures for Java William H. Ford William R. Topp Chapter 24 Graphs and Paths Bret Ford © 2005, Prentice Hall © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology n A graph consists of a set of vertices V, along with

Graph Terminology n A graph consists of a set of vertices V, along with a set of edges E that connect pairs of vertices. An edge e = (vi, vj) connects vertices vi and vj. n A self-loop is an edge that connects a vertex to itself. We assume that none of our graphs have self-loops. n Vertices = {v 1, v 2, v 3, …, vm} Edges = {e 1, e 2, e 3, …, en} © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) n n n The degree of a vertex is the number

Graph Terminology (continued) n n n The degree of a vertex is the number of edges originating at the vertex. Two vertices in a graph are adjacent (neighbors) if there is an edge connecting the vertices. A path between vertices v and w is a series of edges leading from v to w. The path length is the number of edges in the path. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) n n n A path is simple if all its edges

Graph Terminology (continued) n n n A path is simple if all its edges are distinct. A cycle is a simple path that starts and ends on the same vertex. A graph is connected if there is a path between any pair of distinct vertices. A complete graph is a connected graph in which each pair of vertices is linked by an edge. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) n n A graph described until now is termed an undirected

Graph Terminology (continued) n n A graph described until now is termed an undirected graph. Movement between vertices can occur in either direction. In a digraph, edges have a direction. There might be an edge from v to w but no edge from w to v. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) n n n In a digraph, a directed path (path) connecting

Graph Terminology (continued) n n n In a digraph, a directed path (path) connecting vertices vs and ve is a sequence of directed edges that begin at vs and end at ve. The number of the edges that emanate from a vertex v is called the out-degree of the vertex. The number of the edges that terminate in vertex v is the in-degree of the vertex. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) n n A digraph is strongly connected if there is a

Graph Terminology (continued) n n A digraph is strongly connected if there is a path from any vertex to any other vertex. The digraph is weakly connected if, for each pair of vertices vi and vj, there is either a path P(vi, vj) or a path P(vj, vi). © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Graph Terminology (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Terminology (concluded) n n An acyclic graph has no cycles. Each edge in

Graph Terminology (concluded) n n An acyclic graph has no cycles. Each edge in a weighted digraph, has a cost associated with traversing the edge. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs n The Graph interface specifies all basic graph operations including

Creating and Using Graphs n The Graph interface specifies all basic graph operations including inserting and erasing vertices and edges. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River,

Creating and Using Graphs (continued) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Di. Graph Class n The Di. Graph class implements the Graph interface and

The Di. Graph Class n The Di. Graph class implements the Graph interface and adds other methods that are useful in applications. A constructor creates an empty graph. n The methods in. Degree() and out. Degree() are special methods that access a properties that are unique to a digraph. n The static method read. Graph() builds a graph whose vertices are strings. n © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Di. Graph Class (continued) n Di. Graph method read. Graph() inputs the vertex

The Di. Graph Class (continued) n Di. Graph method read. Graph() inputs the vertex values and the edges from a textfile. n File format: (Number of Edges n) Source 1 Destination 1 Source 2 Destination 2. . . Sourcen Destinationn Weight 1 Weight 2 Weightn © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Di. Graph Class (continued) n The method to. String() provides a representation of

The Di. Graph Class (continued) n The method to. String() provides a representation of a graph. For each vertex, the string gives the list of adjacent vertices along with the weight for the corresponding edge. The information for each vertex also includes its in-degree and out-degree. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Di. Graph Class (continued) File samplegraph. dat 5 // data for the vertices

The Di. Graph Class (continued) File samplegraph. dat 5 // data for the vertices A B C D E 6 // data for the edges A B 3 A C 2 B C 6 C B 4 C D 1 E B 5 // input vertices, edges, and weights from samplegraph. dat Di. Graph g = Di. Graph. read. Graph("samplegraph. dat"); // display the graph System. out. println(g) © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

The Di. Graph Class (continued) Output: A: in-degree 0 Edges: B(3) B: in-degree 3

The Di. Graph Class (continued) Output: A: in-degree 0 Edges: B(3) B: in-degree 3 Edges: C(6) C: in-degree 2 Edges: B(4) D: in-degree 1 Edges: E: in-degree 0 Edges: B(5) out-degree 2 C(2) out-degree 1 out-degree 2 D(1) out-degree 0 out-degree 1 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Program 24. 1 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (continued) import java. io. File. Not. Found. Exception; import ds. util.

Program 24. 1 (continued) import java. io. File. Not. Found. Exception; import ds. util. Set; import ds. util. Iterator; import ds. util. Di. Graph; public class Program 24_1 { public static void main(String[] args) throws File. Not. Found. Exception { // construct graph with vertices of type // String by reading from the file "graph. IO. dat" Di. Graph<String> g = Di. Graph. read. Graph("graph. IO. dat"); String vtx. Name; // sets for vertex. Set() and adjacent // vertices (neighbors) Set<String> vtx. Set, neighbor. Set; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (continued) // output number of vertices and edges System. out. println("Number

Program 24. 1 (continued) // output number of vertices and edges System. out. println("Number of vertices: " + g. number. Of. Vertices()); System. out. println("Number of edges: " + g. number. Of. Edges()); // properties relative to vertex A System. out. println("in. Degree for A: " + g. in. Degree("A")); System. out. println("out. Degree for A: " + g. out. Degree("A")); System. out. println("Weight e(A, B): " + g. get. Weight("A", "B")); // delete edge with weight 2 g. remove. Edge("B", "A"); // delete vertex "E" and edges (E, C), // (C, E) and (D, E) g. remove. Vertex("E"); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (continued) /* add and update attributes of the graph */ //

Program 24. 1 (continued) /* add and update attributes of the graph */ // increase weight from 4 to 8 g. set. Weight("A", "B", 8); // add vertex F g. add. Vertex("F"); // add edge (F, D) with weight 3 g. add. Edge("F", "D", 3); // after all updates, output the graph // and its properties System. out. println("After all the graph updates"); System. out. println(g); // get the vertices as a Set and // create set iterator vtx. Set = g. vertex. Set(); Iterator vtx. Iter = vtx. Set. iterator(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (concluded) // scan the vertices and display // the set of

Program 24. 1 (concluded) // scan the vertices and display // the set of neighbors while(vtx. Iter. has. Next()) { vtx. Name = (String)vtx. Iter. next(); neighbor. Set = g. get. Neighbors(vtx. Name); System. out. println(" Neighbor set for " + "vertex " + vtx. Name + " is " + neighbor. Set); } } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (Run) Number of vertices: 5 Number of edges: 8 in. Degree

Program 24. 1 (Run) Number of vertices: 5 Number of edges: 8 in. Degree for A: 1 out. Degree for A: 3 Weight e(A, B): 4 After all the graph updates A: in-degree 0 out-degree Edges: B(8) C(7) D(6) B: in-degree 2 out-degree Edges: C: in-degree 1 out-degree Edges: B(3) D: in-degree 2 out-degree Edges: F: in-degree 0 out-degree Edges: D(3) 3 0 1 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 1 (Run, concluded) Neighbor Neighbor set set set for for for vertex

Program 24. 1 (Run, concluded) Neighbor Neighbor set set set for for for vertex vertex D F A B C is is is [] [D, B, C] [] [B] © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Traversal Algorithms n In general, graphs do not have a vertex, like a

Graph Traversal Algorithms n In general, graphs do not have a vertex, like a root, that initiates unique paths to each of the vertices. From any starting vertex in a graph, it might not be possible to search all of the vertices. In addition, a graph could have a cycle that results in multiple visits to a vertex. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Traversal Algorithms (continued) n n The breadth-first search visits vertices in the order

Graph Traversal Algorithms (continued) n n The breadth-first search visits vertices in the order of their path length from a starting vertex. It may not visit every vertex of the graph The depth-first search traverses all the vertices of a graph by making a series of recursive calls that follow paths through the graph. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Graph Traversal Algorithms (continued) n Graph algorithms discern the state of a vertex during

Graph Traversal Algorithms (continued) n Graph algorithms discern the state of a vertex during the algorithm by using the colors WHITE, GRAY, and BLACK. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All

Breadth-First Search Algorithm © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm (continued) n n Color all vertices of the sample graph WHITE

Breadth-First Search Algorithm (continued) n n Color all vertices of the sample graph WHITE and push the starting vertex (A) onto the queue visit. Queue. Pop A from the queue, color it BLACK, and insert it into visit. List, which is the list of visited vertices. Push all WHITE neighbors onto the queue. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm (continued) n Pop B from the queue and place it in

Breadth-First Search Algorithm (continued) n Pop B from the queue and place it in visit. List with color BLACK. The only adjacent vertex for B is D, which is still colored WHITE. Color D GRAY and add it to the queue © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm (continued) n Pop C and place it in visit. List. The

Breadth-First Search Algorithm (continued) n Pop C and place it in visit. List. The adjacent vertex G is GRAY. No new vertices enter the queue. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm (continued) n Pop vertex G from the queue and place it

Breadth-First Search Algorithm (continued) n Pop vertex G from the queue and place it in visit. List. G has no adjacent vertices, so pop D from the queue. The neighbors, E and F, enter the queue. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Algorithm (continued) n Continue in this fashion until the queue is empty.

Breadth-First Search Algorithm (continued) n Continue in this fashion until the queue is empty. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Implementing Breadth-First Search n Define public enum Vertex. Color { WHITE, GRAY, BLACK }

Implementing Breadth-First Search n Define public enum Vertex. Color { WHITE, GRAY, BLACK } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Implementing Breadth-First Search (continued) n The Di. Graph class declares three methods that access

Implementing Breadth-First Search (continued) n The Di. Graph class declares three methods that access and update the color attribute of a vertex. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Implementing Breadth-First Search (continued) n The method bfs() returns a list of vertices visited

Implementing Breadth-First Search (continued) n The method bfs() returns a list of vertices visited during the breadth‑first search from a starting vertex. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

bfs() // perform the breadth-first traversal // from s. Vertex and return the list

bfs() // perform the breadth-first traversal // from s. Vertex and return the list // of visited vertices public static <T> Linked. List<T> bfs( Di. Graph<T> g, T s. Vertex) { // queue stores adjacent vertices; list // stores visited vertices Linked. Queue<T> visit. Queue = new Linked. Queue<T>(); Linked. List<T> visit. List = new Linked. List<T>(); // set and iterator retrieve and scan // neighbors of a vertex Set<T> edge. Set; Iterator<T> edge. Iter; T curr. Vertex = null, neighbor. Vertex = null; © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

bfs() (continued) // check that starting vertex is valid if (!g. contains. Vertex(s. Vertex))

bfs() (continued) // check that starting vertex is valid if (!g. contains. Vertex(s. Vertex)) throw new Illegal. Argument. Exception( "bfs(): starting vertex not in the graph"); // color all vertices WHITE g. color. White(); // initialize queue with starting vertex visit. Queue. push(s. Vertex); while (!visit. Queue. is. Empty()) { // remove a vertex from the queue, color // it black, and add to the list of // visited vertices curr. Vertex = visit. Queue. pop(); g. set. Color(curr. Vertex, Vertex. Color. BLACK); visit. List. add(curr. Vertex); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

bfs() (continued) // obtain the set of neighbors for current vertex edge. Set =

bfs() (continued) // obtain the set of neighbors for current vertex edge. Set = g. get. Neighbors(curr. Vertex); // sequence through the neighbors and look // for vertices that have not been visited edge. Iter = edge. Set. iterator(); while (edge. Iter. has. Next()) { neighbor. Vertex = edge. Iter. next(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

bfs() (concluded) if (g. get. Color(neighbor. Vertex) == Vertex. Color. WHITE) { // color

bfs() (concluded) if (g. get. Color(neighbor. Vertex) == Vertex. Color. WHITE) { // color unvisited vertex GRAY and // push it onto queue g. set. Color(neighbor. Vertex, Vertex. Color. GRAY); visit. Queue. push(neighbor. Vertex); } } } return visit. List; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Running Time of Breadth-First Search n The running time for the breadth-first search is

Running Time of Breadth-First Search n The running time for the breadth-first search is O(V + E), where V is the number of vertices and E is the number of edges. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Example // create a graph g and declare start. Vertex and visit.

Breadth-First Search Example // create a graph g and declare start. Vertex and visit. List Di. Graph<String> g = Di. Graph. read. Graph("bfsgraph. dat"); String start. Vertex; List<String> visit. List; . . . // call bfs() with arguments g and start. Vertx visit. List = Di. Graphs. bfs(g, start. Vertex); // output the visit. List System. out. println("BFS visit. List from " + start. Vertex + ": " + visit. List); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Breadth-First Search Example (concluded) Output: Run BFS 1: (start. Vertex = "A") visit. List

Breadth-First Search Example (concluded) Output: Run BFS 1: (start. Vertex = "A") visit. List from A: [A, G, B, C, D, E, F] 2: (start. Vertex = "D") visit. List from D: [D, E, F, G] 3: (start. Vertex = "E") visit. List from E: [E] © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit n The depth-first visit algorithm is modeled after the recursive postorder scan

Depth-First Visit n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit (continued) n n Color all vertices WHITE. A vertex is colored GRAY

Depth-First Visit (continued) n n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit (continued) n Backtrack to the previous recursive step and look for another

Depth-First Visit (continued) n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit (continued) n n n n n Discover A (color GRAY) Discover B

Depth-First Visit (continued) n n n n n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit (continued) n n The depth‑first visit is a recursive algorithm that distinguishes

Depth-First Visit (continued) n n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit (continued) n An edge that connects a vertex to a neighbor that

Depth-First Visit (continued) n An edge that connects a vertex to a neighbor that has color GRAY is called a back edge. n A depth-first visit has a cycle if and only if it has a back edge. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

dfs. Visit() // depth-first visit assuming a WHITE starting // vertex; dfs. List contains

dfs. Visit() // depth-first visit assuming a WHITE starting // vertex; dfs. List contains the visited vertices in // reverse order of finishing time; when check. For. Cycle // is true, throws Illegal. Path. State. Exception if it // detects a cycle public static <T> void dfs. Visit(Di. Graph<T> g, T s. Vertex, Linked. List<T> dfs. List, boolean check. For. Cycle) { T neighbor. Vertex; Set<T> edge. Set; // iterator to scan the adjacency set of a vertex Iterator<T> edge. Iter; Vertex. Color color; if (!g. contains. Vertex(s. Vertex)) throw new Illegal. Argument. Exception( "dfs. Visit(): vertex not in the graph"); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

dfs. Visit() (continued) // color vertex GRAY to note its discovery g. set. Color(s.

dfs. Visit() (continued) // color vertex GRAY to note its discovery g. set. Color(s. Vertex, Vertex. Color. GRAY); edge. Set = g. get. Neighbors(s. Vertex); // sequence through the adjacency set and look // for vertices that are not yet discovered // (colored WHITE); recursively call dfs. Visit() // 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 check. For. Cycle is true, // throw an exception edge. Iter = edge. Set. iterator(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

dfs. Visit() (concluded) while (edge. Iter. has. Next()) { neighbor. Vertex = edge. Iter.

dfs. Visit() (concluded) while (edge. Iter. has. Next()) { neighbor. Vertex = edge. Iter. next(); color = g. get. Color(neighbor. Vertex); if (color == Vertex. Color. WHITE) dfs. Visit(g, neighbor. Vertex, dfs. List, check. For. Cycle); else if (color == Vertex. Color. GRAY && check. For. Cycle) throw new Illegal. Path. State. Exception( "dfs. Visit(): graph has a cycle"); } // finished with vertex s. Vertex; make it BLACK // and add it to the front of dfs. List g. set. Color(s. Vertex, Vertex. Color. BLACK); dfs. List. add. First(s. Vertex); } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit Example Linked. List<String> finish. Order = new Linked. List<String>(); g. color. White();

Depth-First Visit Example Linked. List<String> finish. Order = new Linked. List<String>(); g. color. White(); Di. Graphs. dfs. Visit(g, "B", finish. Order, false); Output: finish. Order: [B, D, E, F, C] © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Visit Example (concluded) finish. Order = new Linked. List<String>(); g. color. White(); try

Depth-First Visit Example (concluded) finish. Order = new Linked. List<String>(); g. color. White(); try { Di. Graphs. dfs. Visit(g, "E", finish. Order, true); System. out. println("finish. Order: " + finish. Order); } catch (Illegal. Path. State. Exception ipse) { System. out. println(ipse. get. Message()); } Output: dfs. Visit(): cycle involving vertices D and E © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Search Algorithm n n Depth‑first search begins with all WHITE vertices and performs

Depth-First Search Algorithm n n 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

dfs() // depth-first search; dfs. List contains all // the graph vertices in the

dfs() // depth-first search; dfs. List contains all // the graph vertices in the reverse order // of their finishing times public static <T> void dfs(Di. Graph<T> g, Linked. List<T> dfs. List) { Iterator<T> graph. Iter; T vertex = null; // clear dfs. List. clear(); // initialize all vertices to WHITE g. color. White(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

dfs() (concluded) // call dfs. Visit() for each WHITE vertex graph. Iter = g.

dfs() (concluded) // call dfs. Visit() for each WHITE vertex graph. Iter = g. vertex. Set(). iterator(); while (graph. Iter. has. Next()) { vertex = graph. Iter. next(); if (g. get. Color(vertex) == Vertex. Color. WHITE) dfs. Visit(g, vertex, dfs. List, false); } } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Running Time for Depth-First Search n An argument similar to that for the breadth-first

Running Time for Depth-First Search n An argument similar to that for the breadth-first search shows 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. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Depth-First Search Example dfs. Visit() starting at E followed by dfs. Visit() starting at

Depth-First Search Example dfs. Visit() starting at E followed by dfs. Visit() starting at A dfs. List: [A, B, C, E, F, G, D] © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Acyclic Graphs n To check for a cycle anywhere in a graph, traverse all

Acyclic Graphs n To check for a cycle anywhere in a graph, traverse all of the vertices by using multiple calls to dfs. Visit(). n 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 dfs. Visit(). The method, with check. For. Cycle set to true, identifies the cycle. © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

acyclic() // determine if the graph is acyclic public static <T> boolean acyclic(Di. Graph<T>

acyclic() // determine if the graph is acyclic public static <T> boolean acyclic(Di. Graph<T> g) { // use for calls to dfs. Visit() Linked. List<T> dfs. List = new Linked. List<T>(); Iterator<T> graph. Iter; T vertex = null; // initialize all vertices to WHITE g. color. White(); // call dfs. Visit() for each WHITE vertex; catch // an Illegal. Path. State. Exception in a call to // dfs. Visit() try { // call dfs. Visit() for each WHITE vertex graph. Iter = g. vertex. Set(). iterator(); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

acyclic() (concluded) while (graph. Iter. has. Next()) { vertex = graph. Iter. next(); if

acyclic() (concluded) while (graph. Iter. has. Next()) { vertex = graph. Iter. next(); if (g. get. Color(vertex) == Vertex. Color. WHITE) dfs. Visit(g, vertex, dfs. List, true); } } catch (Illegal. Path. State. Exception iae) { return false; } return true; } © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 2 import java. io. File. Not. Found. Exception; import ds. util. Di.

Program 24. 2 import java. io. File. Not. Found. Exception; import ds. util. Di. Graphs; public class Program 24_2 { public static void main(String[] args) throws File. Not. Found. Exception { Di. Graph<String> g = Di. Graph. read. Graph("cycle. dat"); // determine if the graph is acyclic if (Di. Graphs. acyclic(g)) System. out. println("Graph is acyclic"); else System. out. println("Graph is not acyclic"); © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.

Program 24. 2 (concluded) // add edge (E, B) to create a cycle System.

Program 24. 2 (concluded) // add edge (E, B) to create a cycle System. out. print(" Adding edge (E, B): "); g. add. Edge("E", "B", 1); // retest the graph to see if it is acyclic if (Di. Graphs. 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 © 2005 Pearson Education, Inc. , Upper Saddle River, NJ. All rights reserved.