Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 25 Graph.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 25 Graph."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 25 Graph Algorithms Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Topological Sort Topological sort is the list (in reverse order) of vertices returned by the depth- first search of an acyclic graph. Topological sort is the list (in reverse order) of vertices returned by the depth- first search of an acyclic graph. Possible topological sort: R37 R137 R51 R63 R53 R151 R173 R263

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Topological Sort (continued) The topologicalSort() method returns a list of vertices. If P(v,w) is a path from v to w, then v occurs before w in the list. The topologicalSort() method returns a list of vertices. If P(v,w) is a path from v to w, then v occurs before w in the list. The dfs() algorithm builds the list of visits to the vertices by making repeated calls to dfsVisit(). The dfs() algorithm builds the list of visits to the vertices by making repeated calls to dfsVisit().

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Topological Sort (continued)

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.topologicalSort() // find a topological sort of an acyclic graph public static void topologicalSort(DiGraph g, LinkedList tlist) { Iterator graphIter; T vertex = null; // clear the list that will contain the sort tlist.clear(); g.colorWhite();

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. topologicalSort() (continued) // cycle through the vertices, calling dfsVisit() // for each WHITE vertex; check for a cycle try { // 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, tlist, true); }

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. topologicalSort() (concluded) catch (IllegalPathStateException ipse) { throw new IllegalPathStateException( "topologicalSort(): graph has a cycle"); }

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time for Topological Sort The topological sort uses the algorithm for dfs(), so its running time is also O(V+E), where V is the number of vertices in the graph and E is the number of edges. The topological sort uses the algorithm for dfs(), so its running time is also O(V+E), where V is the number of vertices in the graph and E is the number of edges.

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Strongly Connected Components Any graph can be partitioned into a unique set of strong components. Any graph can be partitioned into a unique set of strong components.

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Strongly Connected Components (continued) The algorithm for finding the strong components of a directed graph G uses the transpose of the graph. The algorithm for finding the strong components of a directed graph G uses the transpose of the graph. The transpose G T has the same set of vertices V as graph G but a new edge set consisting of the edges of G but with the opposite direction. The transpose G T has the same set of vertices V as graph G but a new edge set consisting of the edges of G but with the opposite direction.

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Strongly Connected Components (continued) Execute the depth-first search dfs() for the graph G which creates the list dfsList consisting of the vertices in G in the reverse order of their finishing times. Execute the depth-first search dfs() for the graph G which creates the list dfsList consisting of the vertices in G in the reverse order of their finishing times. Generate the transpose graph G T. Generate the transpose graph G T. Using the order of vertices in dfsList, make repeated calls to dfsVisit() for vertices in G T. The list returned by each call is a strongly connected component of G. Using the order of vertices in dfsList, make repeated calls to dfsVisit() for vertices in G T. The list returned by each call is a strongly connected component of G.

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Strongly Connected Components (continued)

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Strongly Connected Components (continued) dfsList: [A, B, C, E, D, G, F] Using the order of vertices in dfsList, make successive calls to dfsVisit() for graph G T Vertex A: dfsVisit(A) returns the list [A, C, B] of vertices reachable from A in G T. Vertex E: The next unvisited vertex in dfsList is E. Calling dfsVisit(E) returns the list [E]. Vertex D: The next unvisited vertex in dfsList is D; dfsVisit(D) returns the list [D, F, G] whose elements form the last strongly connected component..

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.strongComponents() // find the strong components of the graph; // each element of component is a LinkedList // of the elements in a strong component public static void strongComponents(DiGraph g, ArrayList > component) { T currVertex = null; // list of vertices visited by dfs() for graph g LinkedList dfsList = new LinkedList (); // list of vertices visited by dfsVisit() // for g transpose LinkedList dfsGTList = null; // used to scan dfsList Iterator gIter; // transpose of the graph DiGraph gt = null;

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. strongComponents() (continued) // clear the return vector component.clear(); // execute depth-first traversal of g dfs(g, dfsList); // compute gt gt = transpose(g); // initialize all vertices in gt to WHITE (unvisited) gt.colorWhite();

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. strongComponents() (continued) // call dfsVisit() for gt from vertices in dfsList gIter = dfsList.iterator(); while(gIter.hasNext()) { currVertex = gIter.next(); // call dfsVisit() only if vertex // has not been visited if (gt.getColor(currVertex) == VertexColor.WHITE) {

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. strongComponents() (concluded) // create a new LinkedList to hold // next strong component dfsGTList = new LinkedList (); // do dfsVisit() in gt for starting // vertex currVertex dfsVisit(gt, currVertex, dfsGTList, false); // add strong component to the ArrayList component.add(dfsGTList); }

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time of strongComponents() Recall that the depth-first search has running time O(V+E), and the computation for G T is also O(V+E). It follows that the running time for the algorithm to compute the strong components is O(V+E). Recall that the depth-first search has running time O(V+E), and the computation for G T is also O(V+E). It follows that the running time for the algorithm to compute the strong components is O(V+E).

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Graph Optimization Algorithms Dijkstra's algorithm computes minimum path weight from a specified vertex to all other vertices in the graph. Dijkstra's algorithm computes minimum path weight from a specified vertex to all other vertices in the graph. The breadth ‑ first search can be used to find the shortest path from a specific vertex to all the other vertices in the graph. The breadth ‑ first search can be used to find the shortest path from a specific vertex to all the other vertices in the graph. Minimum spanning tree for a connected, undirected graph is the set of edges that connect all vertices in the graph with the smallest total weight. Minimum spanning tree for a connected, undirected graph is the set of edges that connect all vertices in the graph with the smallest total weight.

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm The breadth-first search can be modified to find shortest paths. Begin at vertex sVertex and visit its neighbors (path length 1) followed by vertices with successively larger path lengths. The algorithm fans out from sVertex along paths of adjacent vertices until it visits all vertices reachable from sVertex. The breadth-first search can be modified to find shortest paths. Begin at vertex sVertex and visit its neighbors (path length 1) followed by vertices with successively larger path lengths. The algorithm fans out from sVertex along paths of adjacent vertices until it visits all vertices reachable from sVertex.

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued) Each vertex must maintain a record of its parent and its path length from sVertex. The DiGraph class provides methods that allow the programmer to associate two fields of information with a vertex. Each vertex must maintain a record of its parent and its path length from sVertex. The DiGraph class provides methods that allow the programmer to associate two fields of information with a vertex. One field identifies the parent of a vertex and the other field is an integer dataValue associated with the vertex. The method initData() assigns a representation for  to each dataValue field of the graph vertices. One field identifies the parent of a vertex and the other field is an integer dataValue associated with the vertex. The method initData() assigns a representation for  to each dataValue field of the graph vertices.

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued)

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued) A breadth ‑ first search visit to a vertex defines a path of shortest length from the starting vertex. A breadth ‑ first search visit to a vertex defines a path of shortest length from the starting vertex. The parent field of the vertex determines the order of vertices from the starting vertex. The parent field of the vertex determines the order of vertices from the starting vertex.

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued) Start the algorithm with sVertex = C. In the vertex, set the dataValue (path length) to 0 and make sVertex its own parent. Initialize the queue by adding C as the first element. Start the algorithm with sVertex = C. In the vertex, set the dataValue (path length) to 0 and make sVertex its own parent. Initialize the queue by adding C as the first element.

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued) At each step, the algorithm updates the data value (path length from starting vertex) and the parent reference before a vertex enters the queue. At the conclusion of the algorithm (queue becomes empty), the data value for a vertex is the shortest path length from the starting vertex. At each step, the algorithm updates the data value (path length from starting vertex) and the parent reference before a vertex enters the queue. At the conclusion of the algorithm (queue becomes empty), the data value for a vertex is the shortest path length from the starting vertex.

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued)

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Shortest Path Algorithm (continued) shortestPath() finds the shortest path length from v s to all of the vertices in the graph. The value is  if the vertex is not reachable from v s. shortestPath() finds the shortest path length from v s to all of the vertices in the graph. The value is  if the vertex is not reachable from v s.

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.shortestPath() // use the breadth-first traversal algorithm to // determine the minimum number of edges in any // path from sVertex to all vertices in the graph // reachable from sVertex; upon return, the dataValue // field of each vertex in g is either the shortest // path length to the vertex or is INFINITY if the // vertex was not reachable from sVertex; call // path(g, sVertex, v) to find the shortest path // from sVertex to v public static void shortestPath(DiGraph g, T sVertex) { // BFS uses a queue to store adjacent vertices LinkedQueue visitQueue = new LinkedQueue (); Set edgeSet; Iterator edgeIter; T currVertex = null, neighborVertex = null; int currentPathLength;

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. shortestPath() (continued) if (!g.containsVertex(sVertex)) throw new IllegalArgumentException( "shortestPath(): starting vertex not " + "in the graph"); // set each vertex data value to INFINITY g.initData(); // sVertex is its own parent and the shortest path // to itself has length 0 g.setParent(sVertex, sVertex); g.setData(sVertex, 0); // insert starting vertex into the queue visitQueue.push(sVertex); // process vertices until the queue is empty while (!visitQueue.isEmpty()) { // delete a queue entry currVertex = visitQueue.pop();

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. shortestPath() (concluded) edgeSet = g.getNeighbors(currVertex); // sequence through the edge set and look // for vertices that have not been visited; // assign each such vertex a dataValue of // currentPathLength + 1 currentPathLength = g.getData(currVertex); edgeIter = edgeSet.iterator(); while (edgeIter.hasNext()) { neighborVertex = edgeIter.next(); if (g.getData(neighborVertex) == INFINITY) { g.setData(neighborVertex, currentPathLength + 1); g.setParent(neighborVertex, currVertex); visitQueue.push(neighborVertex); }

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.path() // returns the path computed by a graph algorithm // from sVertex to eVertex public static LinkedList path(DiGraph g, T sVertex, T eVertex) { T currVertex = eVertex; LinkedList path = new LinkedList (); if (g.getData(eVertex) == DiGraphs.INFINITY) return path; while (!currVertex.equals(sVertex)) { path.addFirst(currVertex); currVertex = g.getParent(currVertex); } path.addFirst(sVertex); return path; }

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time for shortestPath() The shortest-path algorithm simply uses the breadth-first search. There is additional O(V) overhead to initialize the dateValue for each vertex. With the breadth-first search having running time O(V + E), the total running time for the shortest-path is O(V + E). The shortest-path algorithm simply uses the breadth-first search. There is additional O(V) overhead to initialize the dateValue for each vertex. With the breadth-first search having running time O(V + E), the total running time for the shortest-path is O(V + E).

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm The minimum path problem is to determine a path of minimum weight from a starting vertex v s to each reachable vertex in the graph. The path may contain more vertices than the shortest path from v s. The minimum path problem is to determine a path of minimum weight from a starting vertex v s to each reachable vertex in the graph. The path may contain more vertices than the shortest path from v s.

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) Three paths, A-B-E, A-C-E, and A-D-E, have path length 2, with weights 15, 17, and 13 respectively. The minimum path is A-C-D-E, with weight 11 but path length 3.

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) Dijkstra's algorithm uses a priority queue with elements that store the minimum path weight from the starting vertex. Dijkstra's algorithm uses a priority queue with elements that store the minimum path weight from the starting vertex. The DiGraphs static inner class MinInfo contains a vertex reference and the path weight as variables. The vertex is the ending vertex on a path from the starting vertex and pathWeight is sum of the weights for the edges of the path. The class implements the Comparable interface using the pathWeight attribute. The DiGraphs static inner class MinInfo contains a vertex reference and the path weight as variables. The vertex is the ending vertex on a path from the starting vertex and pathWeight is sum of the weights for the edges of the path. The class implements the Comparable interface using the pathWeight attribute.

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. MinInfo Class // priority queue data used by minimumPath() and // minSpanningTree() algorithms private static class MinInfo implements Comparable > { public T endV; public int pathWeight; public int compareTo(MinInfo item) { if (pathWeight < item.pathWeight) return -1; else if (pathWeight == item.pathWeight) return 0; else return 1; }

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) Each step in the algorithm removes a MinInfo object from the priority queue and identifies the vertex. Since no subsequent step could find a new path to the vertex with a smaller weight, we have the minimum path weight and can color the vertex BLACK (visited). Each step in the algorithm removes a MinInfo object from the priority queue and identifies the vertex. Since no subsequent step could find a new path to the vertex with a smaller weight, we have the minimum path weight and can color the vertex BLACK (visited).

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) For each neighbor that is not BLACK, check whether adding the edge to the minimum path from the starting vertex to the current vertex will create a "better" path from the starting vertex. If the new path is better, create a MinInfo object and insert it into the priority queue. Update the data value and parent reference for the neighbor. For each neighbor that is not BLACK, check whether adding the edge to the minimum path from the starting vertex to the current vertex will create a "better" path from the starting vertex. If the new path is better, create a MinInfo object and insert it into the priority queue. Update the data value and parent reference for the neighbor.

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) The algorithm terminates whenever the priority queue becomes empty or when the number of visited vertices matches the vertex size of the graph. The algorithm terminates whenever the priority queue becomes empty or when the number of visited vertices matches the vertex size of the graph.

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued)

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) Assume a better path than the one found by Dijkstra's Algorithm exists. Assume a better path than the one found by Dijkstra's Algorithm exists. Assume this second path and the Dijkstra path are the same up to vertex u and that the weight of the path P(v s, v e ) found by Dijkstra's algorithm is W. The better (second) path has an intermediate vertex x that is in the priority queue but is not marked. The weight to x is Assume this second path and the Dijkstra path are the same up to vertex u and that the weight of the path P(v s, v e ) found by Dijkstra's algorithm is W. The better (second) path has an intermediate vertex x that is in the priority queue but is not marked. The weight to x is w = weight for P (v s, x) = weight of P(v s,u) + weight(u,x)

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued)

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dijkstra's Minimum-Path Algorithm (continued) The weight w must be less than W, so the MinInfo(x, w) object will come out of the priority queue before the path found by the algorithm. Continuing in this way, all the vertices on the better path will come out of the priority queue, and the algorithm will find the optimal path, contradicting our assumption that the algorithm does not find the minimum path. The weight w must be less than W, so the MinInfo(x, w) object will come out of the priority queue before the path found by the algorithm. Continuing in this way, all the vertices on the better path will come out of the priority queue, and the algorithm will find the optimal path, contradicting our assumption that the algorithm does not find the minimum path.

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.minimumPath() // find the path with minimum total weight from // sVertex to each vertex in the graph reachable // from sVertex; upon return, the dataValue field // of each vertex in g is either the minimum path // weight to the vertex or is INFINITY if the // vertex was not reachable from sVertex; call // path(g, sVertex, v) to find the minimum path // from sVertex to v public static void minimumPath( DiGraph g, T sVertex) { T currVertex = null, neighborVertex = null; // heap (priority queue) that stores MinInfo objects HeapPQueue > minPathPQ = new HeapPQueue >(new Less >()); // used when inserting MinInfo entries into the // priority queue or erasing entries MinInfo vertexData = null;

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minimumPath() (continued) // edgeSet is edge set of vertex we are visiting; // edgeIter is used to traverse edgeSet Set edgeSet; Iterator edgeIter; // computed minimum weight int newMinWeight, numVisited = 0, numVertices;... } // terminate on an empty priority queue or when // the number of vertices visited is numVertices while (numVisited < numVertices && !minPathPQ.isEmpty()) { // delete a priority queue entry and record its vertex vertexData = minPathPQ.pop(); currVertex = vertexData.endV;

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minimumPath() (continued) // if currVertex is BLACK, we have already // found the optimal path from sVertex to currVertex if (g.getColor(currVertex) != VertexColor.BLACK) { // mark the vertex so we don't look at it // again and increment numVisited g.setColor(currVertex, VertexColor.BLACK); numVisited++; // find all neighbors of the current vertex; // for each neighbor that has not been visited, // generate a MinInfo object and insert it into // the priority queue provided the total weight // to get to the neighbor is better than the // current dataValue of neighborVertex edgeSet = g.getNeighbors(currVertex); edgeIter = edgeSet.iterator();

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minimumPath() (continued) while (edgeIter.hasNext()) { neighborVertex = edgeIter.next(); if (g.getColor(neighborVertex) == VertexColor.WHITE) { newMinWeight = g.getData(currVertex) + g.getWeight(currVertex, neighborVertex);

48 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minimumPath() (continued) // if we have found a better path to // neighborVertex, create a new MinInfo // object for neighborVertex and push it // onto the priority queue; update the // dataValue and parent of neighborVertex; // NOTE: if neighborVertex is WHITE, its // data value is INFINITY and a new MinInfo // object will enter the priority queue if (newMinWeight < g.getData(neighborVertex)) {

49 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minimumPath() (concluded) vertexData = new MinInfo (); vertexData.endV = neighborVertex; vertexData.pathWeight = newMinWeight; minPathPQ.push(vertexData); g.setData(neighborVertex, newMinWeight); g.setParent(neighborVertex, currVertex); }

50 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time of Dijkstra's Algorithm Dijkstra's algorithm has running time O(V + E log 2 V). Dijkstra's algorithm has running time O(V + E log 2 V).

51 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Path in Acyclic Graphs When the weighted digraph is acyclic, the problem of finding minimum paths is greatly simplified. When the weighted digraph is acyclic, the problem of finding minimum paths is greatly simplified. The depth-first search creates a list of vertices in topolocial order. dfsList : [v 0, v 1,...,v i,..., v n-1 ] The depth-first search creates a list of vertices in topolocial order. dfsList : [v 0, v 1,...,v i,..., v n-1 ] Assume v i is the starting vertex for the minimum-path problem. Vertices in the list v 0 to v i-1 are not reachable from vi. Assume v i is the starting vertex for the minimum-path problem. Vertices in the list v 0 to v i-1 are not reachable from vi.

52 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Path in Acyclic Graphs (continued) After initializing the data value for all of the vertices to , set the data value for v i to 0 and its parent reference to v i. A scan of the vertices in dfsList will find that v 0 through v i-1 have value  and will not be considered. The algorithm discovers v i and iteratively scans the tail of dfsList, proceeding much like Dijkstra's algorithm. After initializing the data value for all of the vertices to , set the data value for v i to 0 and its parent reference to v i. A scan of the vertices in dfsList will find that v 0 through v i-1 have value  and will not be considered. The algorithm discovers v i and iteratively scans the tail of dfsList, proceeding much like Dijkstra's algorithm.

53 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.dagMinimumPath() // in the directed acyclic graph, find the path with // minimum total weight from sVertex to each vertex // reachable from sVertex; upon return, the dataValue // field of each vertex in g is either the minimum path // weight to the vertex or is INFINITY if the vertex // was not reachable from sVertex; call // path(g, sVertex, v) to find the minimum path from // sVertex to v public static void dagMinimumPath( DiGraph g, T sVertex) { LinkedList tlist = new LinkedList (); Iterator topSortIter, setIter; T currVertex, neighborVertex; int w, dataValue; // perform a topological sort of g topologicalSort(g, tlist);

54 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. dagMinimumPath() (continued) // set all dataValues to INFINITY g.initData(); // set dataValue and parent for sVertex g.setData(sVertex, 0); g.setParent(sVertex, sVertex); topSortIter = tlist.iterator(); // sequence through the topological sort and // update the distance to each neighbor while (topSortIter.hasNext()) { // get the next vertex in the topological sort currVertex = topSortIter.next();

55 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. dagMinimumPath() (continued) // get the dataValue of currVertex; if it is // INFINITY, the vertex is not reachable // from sVertex if ((dataValue = g.getData( currVertex)) != INFINITY) { // obtain an iterator for the neighbors // of currVertex setIter = g.getNeighbors(currVertex).iterator(); while (setIter.hasNext()) { // get the next neighbor of currVertex neighborVertex = setIter.next();

56 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. dagMinimumPath() (concluded) // reset dataValue and parent if adding the // edge (currVertex, neighborVertex) to the // path sVertex --> currVertex provides a // better path to neighborVertex w = dataValue + g.getWeight(currVertex, neighborVertex); if (w < g.getData(neighborVertex)) { g.setData(neighborVertex, w); g.setParent(neighborVertex, currVertex); }

57 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Path in Acyclic Graphs (continued) At a vertex v in the sequential scan of dfsList, its current data value is the minimum path weight from v i to v. For there to be a better path, there must be an unvisited vertex, v', reachable from v i that has an edge to v. This is not possible, since topological order guarantees that v' will come earlier in dfsList. At a vertex v in the sequential scan of dfsList, its current data value is the minimum path weight from v i to v. For there to be a better path, there must be an unvisited vertex, v', reachable from v i that has an edge to v. This is not possible, since topological order guarantees that v' will come earlier in dfsList.

58 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Path in Acyclic Graphs (continued)

59 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time for Minimum Path in Acyclic Graphs The algorithm first creates a topological sort of the vertices with running time O(V+E). A loop visits all of the vertices in the graph once and examines edges that eminate from each vertex only once. Access to all of the vertices and edges has running time O(V+E) and so the total running time for the algorithm is O(V+E). The algorithm first creates a topological sort of the vertices with running time O(V+E). A loop visits all of the vertices in the graph once and examines edges that eminate from each vertex only once. Access to all of the vertices and edges has running time O(V+E) and so the total running time for the algorithm is O(V+E).

60 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Spanning Tree A minimum spanning tree for a connected undirected graph is an acyclic set of edges that connect all the vertices of the graph with the smallest possible total weight. A minimum spanning tree for a connected undirected graph is an acyclic set of edges that connect all the vertices of the graph with the smallest possible total weight. A network connects hubs in a system. The minimum spanning tree links all of the nodes in the system with the least amount of cable. A network connects hubs in a system. The minimum spanning tree links all of the nodes in the system with the least amount of cable.

61 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Minimum Spanning Tree (continued)

62 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm The mechanics are very similar to the Dijkstra minimum-path algorithm. The mechanics are very similar to the Dijkstra minimum-path algorithm. The iterative process begins with any starting vertex and maintains two variables minSpanTreeSize and minSpanTreeWeight, which have initial values 0. The iterative process begins with any starting vertex and maintains two variables minSpanTreeSize and minSpanTreeWeight, which have initial values 0. Each step adds a new vertex to the spanning tree. It has an edge of minimal weight that connects the vertex to those already in the minimal spanning tree. Each step adds a new vertex to the spanning tree. It has an edge of minimal weight that connects the vertex to those already in the minimal spanning tree.

63 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued) Prim's algorithm uses a priority queue where elements store a vertex and the weight of an edge that can connect it to the tree. Prim's algorithm uses a priority queue where elements store a vertex and the weight of an edge that can connect it to the tree. When an object comes out of the priority queue, it defines a new edge that connects a vertex to the spanning tree. When an object comes out of the priority queue, it defines a new edge that connects a vertex to the spanning tree.

64 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued)

65 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued)

66 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued)

67 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued)

68 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Prim's Algorithm (continued)

69 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved.minSpanTree() // find the minimum spanning tree for the connected // graph g; g is represented as a digraph with // bidirectional edges of equal weight public static int minSpanTree(DiGraph g, DiGraph MST) { // priority queue that stores MinInfo objects HeapPQueue > minTreePQ = new HeapPQueue >( new Less >()); // used when inserting MinInfo entries // into the priority queue or erasing entries MinInfo vertexData = null; // edgeSet is adjacency set of vertex we are // visiting; edgeIter is an iterator that scans // the list; vertexSet used to traverse graph vertices Set edgeSet, vertexSet; Iterator edgeIter; T sVertex = null, currVertex = null, neighborVertex = null;

70 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minSpanTree() (continued) Iterator graphIter; int edgeWeight; // size of the minimum spanning tree int minSpanTreeSize = 0; // current minimum total weight for spanning tree int minSpanTreeWeight = 0;... } // add vertices until we span the entire graph for (;;) { if (minTreePQ.isEmpty()) throw new IllegalArgumentException( "minSpanTree(): graph is not connected"); // delete a priority queue entry vertexData = minTreePQ.pop(); currVertex = vertexData.endV;

71 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minSpanTree() (continued) // if vertex is not part of the new graph (unvisited) // add the weight of the edge to the total tree weight // and increment the number of vertices in the tree if (g.getColor(currVertex) == VertexColor.WHITE) { minSpanTreeWeight += vertexData.pathWeight; minSpanTreeSize++; // if we spanned all vertices, break if (minSpanTreeSize == g.numberOfVertices()) break; // mark the vertex BLACK so we don't look // at it again g.setColor(currVertex, VertexColor.BLACK); // find all unmarked neighbors of the vertex edgeSet = g.getNeighbors(currVertex); edgeIter = edgeSet.iterator();

72 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minSpanTree() (continued) while (edgeIter.hasNext()) { neighborVertex = edgeIter.next(); // if neighbor is unmarked, check whether // adding the new edge to the tree is better // than using the current edge if (g.getColor(neighborVertex) == VertexColor.WHITE) { edgeWeight = g.getWeight(currVertex,neighborVertex);

73 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. minSpanTree() (concluded) if (edgeWeight < g.getData(neighborVertex)) { // if new edge is a better connection, // create MinInfo object for new vertex; // update dataValue and parent variables vertexData = new MinInfo (); vertexData.endV = neighborVertex; vertexData.pathWeight = edgeWeight; g.setData(neighborVertex, edgeWeight); g.setParent(neighborVertex, currVertex); minTreePQ.push(vertexData); }

74 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Running Time for Prim's Algorithm Like Dijkstra's algorithm, Prim's algorithm has running time O(V + E log 2 V). Like Dijkstra's algorithm, Prim's algorithm has running time O(V + E log 2 V).


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 25 Graph."

Similar presentations


Ads by Google