Download presentation
Presentation is loading. Please wait.
1
Weighted Graphs: Networks
Chapter 31 Weighted Graphs: Networks Chp. 28
2
Networks A Network is a graph whose edges are weighted
Also known as a weighted graph Meaning of “Weight” is application dependent (could be distance, time, money, flow,…) Chp. 28
3
Networks 548 D B 623 320 360 A 200 F 245 345 555 C E 467 Example of a weighted graph. Assume distance between nodes A & B is 623 miles Chp. 28
4
Networks A B C D E F A B C D E F A 0 623 354 0 0 0 623 0 200 548 0 0 B
B C D E F Vertex Vector Adjacency Matrix Representing a weighted graph with an Adjacency Matrix (observe symmetric redundancy) Chp. 28
5
Networks Vertex List Adjacency List A B C D E F B 623 C 345 A 623
Representing a weighted graph with an Adjacency List. Vertex List Adjacency List A B 623 C 345 B A 623 C 200 D 548 C A 345 B 200 D 360 E 467 D B 548 C 360 E 245 F 320 E C 467 D 254 F 555 F D 320 E 555
6
Minimum Spanning Tree Consider a graph G=(V,E)
A spanning tree T for G is a tree that contains all the vertices of V and some edges from E. A Minimum Spanning Tree T (MST) of a network G is such that the sum of the weights is guaranteed to be minimal
7
Minimum Spanning Tree Examples
Assume we have a computer network and the edges are labeled with the distance between nodes. A minimal spanning tree of the network would give us the shortest length of cable required to connect all the computers
8
Minimum Spanning Tree begin T ← ϕ (spanning tree)
Kruskal’s Algorithm: Finding a Minimum Spanning Tree for weighted graph G=(V, E) begin T ← ϕ (spanning tree) VS ← ϕ (vertices in the solution) Construct a min-Heap containing all the edges; for each vertex v ϵ V do add {v } to VS; while |VS|>1 do begin choose (v, w), an edge in min-Heap of lowest cost; delete (v, w) from min-Heap; if v and w are in different sets W1 and W2 in VS then begin replace W1 and W2 in VS by W1 W2 add (v, w) to T; end; The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
9
Example 1: Minimum Spanning Tree
9
10
Example 1: Minimum Spanning Tree cont
Minimum Spanning Tree (weight= 39)
11
Example 2: Minimum Spanning Tree
20 v1 v2 15 4 23 1 v7 v3 v6 9 36 25 16 28 3 v5 v4 17 Find a Minimum Spanning Tree for the graph above. The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
12
Ex2. Minimum Spanning Tree
min-Heap Edge Cost (v1, v7) 1 (v4, v5) 17 (v3, v4) 3 (v1, v2) 20 (v2, v7) 4 (v1, v6) 23 (v3, v7) 9 (v5, v7) 25 (v2, v3) 15 (v5, v6) 28 (v4, v7) 16 (v6, v7) 36 Representing ordered sequence of weighted edges (use a min-Heap instead) The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
13
Ex2. Minimum Spanning Tree
Edge Action Sets in VS (connected components) (v1, v7) 1 Add { v1,v7 }, { v2 }, { v3 }, { v4 }, { v5 }, { v6 } (v3, v4) 3 { v1,v7 }, { v2 }, { v3, v4 }, { v5 }, { v6 } (v2, v7) 4 { v1,v7, v2 }, { v3, v4 }, { v5 }, { v6 } (v3, v7) 9 { v1,v7, v2, v3, v4 }, { v5 }, { v6 } (v2, v3) 15 Reject (v4, v7) 16 (v4, v5) 17 { v1,v7, v2, v3, v4, v5 }, { v6 } (v1, v2) 20 (v1, v6) 23 { v1,v7, v2, v3, v4, v5, v6 } We begin with a forest of individual nodes and finish with a single unified component including all the nodes. An edge is added to combine two disjoint components. An edge is rejected when it forms a closed circuit. The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
14
Ex2. Minimum Spanning Tree
v1 v2 4 23 1 v7 v3 v6 9 3 v5 v4 17 A Minimum Spanning Tree for example graph. Total weight is 57. Chp. 28
15
Ex3. Minimum Spanning Tree
5 D B 6 3 3 A 2 F 2 3 5 C E 4 A Minimum Spanning Tree for example graph. Total weight is 13. Chp. 28
16
Shortest Path Algorithm
There are occasions when we wish to find the shortest path between various vertices. Edsger Dijkstra developed a classic algorithm to solve the single source path routing problem For a node v in the graph G, the algorithm finds the path with lowest cost between that vertex v and every other vertex in G. This is known as “Dijkstra’s Shortest Path Algorithm” Dijkstra, E.W. “A note on two problems in connexion with graphs,” Numerische Mathematik, Vol. 1(1959), Recommended:
17
Shortest Path Algorithm - Example
We want to find the shortest path between A and any other vertex. The total path’s cost to each vertex is denoted with “L: n” 5 A B C D E F 3 6 4 2 L: 6 B 6 L: 0 A A Add node C whose weight is L:3 (better than B’s L:6 ) 3 3 C C L: 3 L: 3 Possible Paths Finding Shortest Path
18
Shortest Path Algorithm - Example
Visited Nodes = { A, C } Adjacent to Visited are { B, D, E } Choose node B with weight L: 5 5 A B C D E F 3 6 4 2 L: 6 L: 6 D B 6 B L: 5 L: 0 L: 5 3 A 2 2 A 3 L: 7 C 3 E 4 L: 3 C L: 3 Possible Paths Shortest Paths
19
Shortest Path Algorithm - Example
5 A B C D E F 3 6 4 2 Visited Nodes = { A, B, C } Adjacent to Visited are { D, E } Choose node D with weight L: 6 L: 6 L: 6 5 D B L: 6 L: 5 B D L: 0 L: 5 3 A 2 2 3 A 3 L: 7 C 3 E 4 L: 3 C L: 3 Possible Paths Shortest Paths
20
Shortest Path Algorithm - Example
Visited Nodes = { A, B, C, D } Adjacent to Visited are { E, F } Choose node E with weight L: 7 5 A B C D E F 3 6 4 2 L: 6 L: 6 D B 3 L: 6 B D L: 5 L: 9 L: 0 3 F L: 5 A 2 2 2 3 A L: 8 3 C 3 E 4 L: 7 L: 3 L: 7 C E L: 3 4 Possible Paths Shortest Paths
21
Shortest Path Algorithm - Example
5 A B C D E F 3 6 4 2 Visited Nodes = { A, B, C, D, E } Adjacent to Visited is { F } Choose node F with weight L: 9 L: 6 L: 6 D B 3 L: 6 L: 9 B D L: 5 3 L: 0 L: 5 3 F A 2 L: 9 2 3 F A L: 12 3 5 L: 7 C 3 E 4 L: 7 L: 3 C E L: 3 4 Possible Paths Shortest Paths
22
Shortest Path Algorithm - Example
Informally, we have done the following: Insert the first vertex into the solution tree From every vertex already in the solution tree, examine the total path length to all adjacent vertices not in the tree Select the edge with the minimum total path weight and insert it in to the tree Repeat step two until all vertices are in the tree
23
Shortest Path Algorithm
Dijkstra’s Algorithm Input: A directed graph G=(V, E), a source node v0 in V, and a function L from edges to nonnegative reals. We take L(vi, vj) to be + if L(vi,vj) is not an edge, and L(v,v)=0. Output: For each vertex v in V, the minimum over all paths P from v0 to v of the sum of the labels of the edges of P. Method: We construct a set of vertices S V such that the shortest path from the source to each vertex v in S lies completely in S. The Array D[v] contains the cost of the current shortest path from v0 to v passing through the vertices of S. Details follow The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman. Addison-Wesley Prentice Hall
24
Shortest Path Algorithm
Dijkstra’s Algorithm begin S ← { v0 } (source node) D[ v0 ] ← 0 for each vertex v ϵ ( V – v0 ) do D[ v ] ← L(v0 v); while ( S V ) do begin choose a vertex w in ( V – S ) such that D[ w ] is a minimum; add w to S; for each v in (V – S) do D[ v ] ← MIN( D[ v ], D[ w ] + L( w, v ) ) [w is in S] end; The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
25
Shortest Path Algorithm
2 Dijkstra’s Algorithm V0 V1 3 10 7 V2 6 V4 4 V3 5 Iteration S w D[w] D[v1] D[v2] D[v3] D[v4] Initial { v0 } - 2 + 10 1 { v0, v1 } v1 5 9 { v0, v1, v2 } v2 3 { v0, v1, v2, v3 } v3 4 { v0, v1, v2, v3, v4 } v4 The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
26
Shortest Path Algorithm
2 Dijkstra’s Algorithm V0 V1 3 7 V2 V4 4 V3 S D[v0] D[v1] D[v2] D[v3] D[v4] Solution { v0, v1, v2, v3, v4 } 2 5 9 The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
27
Shortest Path Algorithm & MSP
2 Dijkstra’s Algorithm V0 V1 3 7 V2 MSP Algorithm V4 4 2 V0 V1 V3 3 Observation: Results are not necessarily the same! V2 V4 V0 10 V1 7 V3 V2 3 2 4 5 6 V4 4 V3 5 The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
28
Topological Sort Topological sorting is a partial-ordering strategy useful for defining the sequence in which events should /could happen. Examples: Course prerequisites must be completed prior to certain course. Morning dressing up schedule Functional Dependencies A DAG (directed acyclic graph) can be used to represent the problem (and its solution) Reference:
29
Topological Sort Possible valid orders: Solution 1 Solution 2
CIS151, CIS260, CIS265, CIS335, CIS340, CIS368, CIS345, CIS485 CIS340, CIS345, CIS335, CIS368,
30
Topological Sort
31
Topological Sort L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges while S is non-empty do { remove a node n from S insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into S } if graph has edges then output error message (graph has at least one cycle) else output message (proposed topologically sorted order: L) Reference:
32
Topological Sort The graph shown to the left has many valid topological sorts, including: 7, 5, 3, 11, 8, 2, 9, (visual left-to-right, top-to-bottom) 3, 5, 7, 8, 11, 2, 9, (smallest-numbered vertex first) 3, 7, 8, 5, 11, 10, 2, 9 5, 7, 3, 8, 11, 10, 9, 2 (fewest edges first) 7, 5, 11, 3, 10, 8, 9, 2 (largest-numbered vertex first) 7, 5, 11, 2, 3, 8, 9, 10 Reference:
33
Biconnected Components
Definition A graph G=(E, V) is biconnected if for every triple of vertices v1, v2, va there exists a path between v1 and v2 not containing va. V2 V5 V2 V1 V3 V4 V1 V4 V6 V3 Biconnected Not Biconnected The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
34
Biconnected Components
Definition A vertex a is said to be an articulation point of G if there exist vertices v and w such that every path between v and w contains a. An undirected connected graph G is biconnected iff it has no articulation points. Biconnected Components: { v1, v2, v3 } { v4, v5, v6 } { v2, v4 } V4 and V2 are articulation points V5 V2 V4 V1 V6 V3 Not Biconnected The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
35
Finding Articulation Points
Procedure dfsLabeling ( Vertice v ) { mark v “visited”; DFSNUMBER[ v ] ⟵ COUNT; COUNT ⟵ COUNT + 1; LOW[ v ] ⟵ DFSNUMBER[ v ]; for each vertex w on adjacencyList(v) do { if w is marked “not visited” then { add edge ( v, w ) to T; FATHER[ w ] ⟵ v dfsLabeling ( w ); if LOW[ w ] DFSNUMBER[ v ] then { a biconnected component has been found; v is a n articulation point; } else { if w is not FATHER[ v ] then LOW[w] ⟵ MIN ( LOW[ v ], FDSNUMBER[ w ] ); The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
36
Finding Articulation Points
(a) Graph G (b) A DFS Labeled Tree for graph G The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
37
Finding Articulation Points
(b) Biconnected Components (a) Graph G The Design and Analysis of Computer Algorithms. Aho, Hopcroft, Ullman
38
Appendix A. Finding Articulation Points – Biconnected Components
public class Driver { // Author: Matos // Date: 8/9/2011 // Goal: (1) Implementing a graph using adjacency list (2) traversing graph using DFS_Numbering to // detect articulation points and biconnected components. (see ppt notes BG & VM 265) public static void main(String[] args) { Graph<String> graph = new Graph<String>(); graph.addVertex("V0"); graph.addVertex("V1"); graph.addVertex("V2"); graph.addVertex("V3"); graph.addVertex("V4"); graph.addVertex("V5"); graph.addVertex("V6"); graph.addVertex("V7"); graph.addVertex("V8"); graph.addVertex("V9"); graph.addEdge(1,2); graph.addEdge(2,9); graph.addEdge(1,9); graph.addEdge(2,3); graph.addEdge(3,8); graph.addEdge(2,8); graph.addEdge(3,4); graph.addEdge(4,5); graph.addEdge(5,6); graph.addEdge(5,7); graph.addEdge(6,4); graph.addEdge(7,4); graph.showData(); // traversing graph using SIMPLE DFS graph.clearVisitedMarkers(); System.out.println("\nDFS"); graph.dfs(1); // traversing graph using DFS_NUMBERING to find all bi-connected components System.out.println("\nDFS Labeling"); graph.dfsLabeling(1); graph.showDataLabels(); }//main }//Driver
39
Appendix A. Finding Articulation Points – Biconnected Components
import java.util.Comparator; public class Edge implements Comparable { int v1; int v2; public Edge(int newV1, int newV2){ if (newV1 <= newV2){ v1= newV1; v2= newV2; } else { v1= newV2; v2= newV1; public void showData(){ System.out.printf("\n[v%d, v%d]", v1, v2); @Override public int compareTo(Object otherEdge) { Edge e = (Edge)otherEdge; if ((v1==e.v1 && v2==e.v2) || (v1==e.v2 && v2==e.v1) ) return 0; else return 1;
40
Appendix A. Finding Articulation Points – Biconnected Components
package csu.matos; import java.util.ArrayList; import java.util.Stack; public class Graph<E> { private ArrayList<E> vertices; private ArrayList< ArrayList<Integer> > neighbors; private ArrayList<Boolean> visitedMarkers; private ArrayList<Integer> father; private ArrayList<Integer> dfsNumber; private ArrayList<Integer> low; int count = 1; Stack<Edge> stack = new Stack<Edge>(); Stack<Edge> stackAlreadyVisited = new Stack<Edge>(); public Graph() { vertices = new ArrayList<E>(); neighbors = new ArrayList< ArrayList<Integer> > (); visitedMarkers = new ArrayList<Boolean>(); father = new ArrayList<Integer>(); dfsNumber = new ArrayList<Integer>(); low = new ArrayList<Integer>(); } public void addVertex(E newVertice){ vertices.add(newVertice); neighbors.add( new ArrayList<Integer>() ); visitedMarkers.add(false); public void addEdge(int v1, int v2){ ArrayList<Integer> adjacent1 = neighbors.get(v1); if (!adjacent1.contains(v2)) neighbors.get(v1).add(v2); ArrayList<Integer> adjacent2 = neighbors.get(v2); if (!adjacent2.contains(v1)) neighbors.get(v2).add(v1); public void showData() { for(int i=0; i<vertices.size(); i++){ System.out.printf("\nVertice[%d]= %s" , i, vertices.get(i));
41
Appendix A. Finding Articulation Points – Biconnected Components
for(int i=0; i<vertices.size(); i++){ System.out.printf("\nneighbors[%d] >> " , i); ArrayList<Integer> adjacent = neighbors.get(i); for(int j=0; j<adjacent.size(); j++){ System.out.printf(" %d", adjacent.get(j)); } public void clearVisitedMarkers(){ for (int i=0; i<visitedMarkers.size(); i++){ visitedMarkers.set(i, false); father.add(0); low.add(0); dfsNumber.add(0); public void dfs(int v){ visitedMarkers.set(v, true); int n; ArrayList<Integer> adjacent = neighbors.get(v); for (int i=0; i<adjacent.size(); i++){ n = adjacent.get(i); if (!visitedMarkers.get(n)){ System.out.printf(" [v%d v%d] ", v, n); dfs(n); // /////////////////////////////////////////////////////////////// public void dfsLabeling(int v){ dfsNumber.set(v, count); count++; low.set(v, dfsNumber.get(v)); int w; w = adjacent.get(i); //Stacking edges pushEdgeBiconnectedComponentStack(v, w);
42
Appendix A. Finding Articulation Points – Biconnected Components
if (!visitedMarkers.get(w)){ // adding node n to solution tree n System.out.printf(" [v%d v%d] ", v, w); father.set(w, v); dfsLabeling(w); System.out.printf("\nback (v,w) (%d,%d)", v, w); System.out.printf("\nlow[%d]: %d low[%d]:%d", v, low.get(v), w, low.get(w) ); if ( low.get(w) >= dfsNumber.get(v)) { System.out.printf("\nBiconnected comp. found.%d Articulation: %d",w, v); popEdgeBiconnectedComponentStack(v,w); } int minValueVW = Math.min(low.get(v), low.get(w)); low.set(v, minValueVW); System.out.printf("\nset1 low[%d]: %d", v, low.get(v)); } else { if ( w != father.get(v)){ int minValueVW = Math.min(low.get(v), dfsNumber.get(w)); System.out.printf("\n!father>> low[%d]: %d dfsN[%d]:%d", v, low.get(v), w, dfsNumber.get(w) ); System.out.printf("\nset2 low[%d]: %d", v, low.get(v)); }//dfsLabeling private void popEdgeBiconnectedComponentStack(int v, int w) { Edge e1; if (v < w) e1 = new Edge(v, w); else e1 = new Edge(w, v); Edge e = null; while (!stack.isEmpty()){ e = stack.pop(); // copy visited/popped edges to stackAlreadyVisisted stackAlreadyVisited.push(e); System.out.printf(" \n>>Binconn [%d, %d] ", e.v1, e.v2); if (e.compareTo(e1)==0){ break;
43
Appendix A. Finding Articulation Points – Biconnected Components
private void pushEdgeBiconnectedComponentStack(int v, int w) { Edge e1; if (v < w) e1 = new Edge(v,w); else e1 = new Edge(w,v); // is this edge already in the stack? boolean found = false; int i=0; Edge e; while ((i<stack.size()) && !found){ e = stack.get(i); if (e.compareTo(e1)==0) found = true; i++; } // has this edge been used already by other component? boolean found2 = false; int i2=0; Edge e2; while ((i2<stackAlreadyVisited.size()) && !found2){ e2 = stackAlreadyVisited.get(i2); if (e2.compareTo(e1)==0) found2 = true; i2++; // insert only new edges (only ONCE!!!) if (!found && !found2) stack.push(e1); public void showDataLabels(){ for (int i=0; i<vertices.size(); i++){ System.out.printf("\nv%d low:%d dfsN:%d father:%d" , i, low.get(i), dfsNumber.get(i), father.get(i) );
44
Appendix A. Finding Articulation Points – Biconnected Components
(console – dfsLabeling ) Biconnected comp. found.5 Articulation: 4 >>Binconn [4, 7] Vertice[0]= V0 >>Binconn [5, 7] Vertice[1]= V1 >>Binconn [4, 6] Vertice[2]= V2 >>Binconn [5, 6] Vertice[3]= V3 >>Binconn [4, 5] Vertice[4]= V4 set1 low[4]: 6 Vertice[5]= V5 !father>> low[4]: 6 dfsN[6]:8 Vertice[6]= V6 set2 low[4]: 6 Vertice[7]= V7 !father>> low[4]: 6 dfsN[7]:9 Vertice[8]= V8 Vertice[9]= V9 back (v,w) (3,4) neighbors[0] >> low[3]: 2 low[4]:6 neighbors[1] >> Biconnected comp. found.4 Articulation: 3 neighbors[2] >> >>Binconn [3, 4] neighbors[3] >> set1 low[3]: 2 neighbors[4] >> back (v,w) (2,3) neighbors[5] >> low[2]: 1 low[3]:2 neighbors[6] >> Biconnected comp. found.3 Articulation: 2 neighbors[7] >> >>Binconn [2, 8] neighbors[8] >> >>Binconn [3, 8] neighbors[9] >> >>Binconn [2, 3] DFS Labeling set1 low[2]: 1 [v1 v2] [v2 v9] !father>> low[2]: 1 dfsN[8]:5 !father>> low[9]: 3 dfsN[1]:1 set2 low[2]: 1 set2 low[9]: 1 back (v,w) (1,2) back (v,w) (2,9) low[1]: 1 low[2]:1 low[2]: 2 low[9]:1 Biconnected comp. found.2 Articulation: 1 set1 low[2]: 1 [v2 v3] [v3 v8] >>Binconn [1, 9] !father>> low[8]: 5 dfsN[2]:2 >>Binconn [2, 9] set2 low[8]: 2 >>Binconn [1, 2] back (v,w) (3,8) set1 low[1]: 1 low[3]: 4 low[8]:2 !father>> low[1]: 1 dfsN[9]:3 set1 low[3]: 2 [v3 v4] [v4 v5] [v5 v6] set2 low[1]: 1 !father>> low[6]: 8 dfsN[4]:6 v0 low:0 dfsN:0 father:0 set2 low[6]: 6 v1 low:1 dfsN:1 father:0 back (v,w) (5,6) v2 low:1 dfsN:2 father:1 low[5]: 7 low[6]:6 v3 low:2 dfsN:4 father:2 set1 low[5]: 6 [v5 v7] v4 low:6 dfsN:6 father:3 !father>> low[7]: 9 dfsN[4]:6 v5 low:6 dfsN:7 father:4 set2 low[7]: 6 v6 low:6 dfsN:8 father:5 back (v,w) (5,7) v7 low:6 dfsN:9 father:5 low[5]: 6 low[7]:6 v8 low:2 dfsN:5 father:3 set1 low[5]: 6 v9 low:1 dfsN:3 father:2 back (v,w) (4,5) low[4]: 6 low[5]:6
45
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
package csu.matos; public class Driver { /************************************************************************************ * Author: Matos * Date: 8/18/2011 * Goal: Compute minimum distance between two nodes * in a directed graph using Dijkstra's algorithm ***********************************************************************************/ public static void main(String[] args) { // demo1. Example from Aho, Hopcroft, Ullman DirectedGraph<String> graph = populateGraph1(); System.out.println("\nMinumum Distance - Dijkstra - Sourve: v0>>> "); graph.minimumDistance(0); graph.showData(); //// demo2. Example from D. Liang //DirectedGraph<String> graph = populateGraph2(); //System.out.println("\nMinumum Distance - Dijkstra - Sourve: v1>>> "); //graph.minimumDistance(1); //graph.showData(); }//main // /////////////////////////////////////////////////////////// private static DirectedGraph<String> populateGraph1(){ DirectedGraph<String> graph = new DirectedGraph<String>(); // taken from "Analysis of Algorithms" Aho, Hopcroft, Ullman graph.addVertice("V0"); graph.addVertice("V1"); graph.addVertice("V2"); graph.addVertice("V3"); graph.addVertice("V4"); graph.addEdge(0,1, 2); graph.addEdge(0,4, 10); graph.addEdge(1,2, 3); graph.addEdge(1,4, 7); graph.addEdge(2,3, 4); graph.addEdge(3,4, 5); graph.addEdge(4,2, 6); return graph; }//demo1
46
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
// /////////////////////////////////////////////////////// private static DirectedGraph<String> populateGraph2(){ // taken from Java Programming by D. Liang // this demo graph is NOT directed (edges go both ways) DirectedGraph<String> graph = new DirectedGraph<String>(); graph.setDirected(false); graph.addVertice("V0"); graph.addVertice("V1"); graph.addVertice("V2"); graph.addVertice("V3"); graph.addVertice("V4"); graph.addVertice("V5"); graph.addVertice("V6"); graph.addEdge(0,1, 8); graph.addEdge(0,2, 1); graph.addEdge(0,5, 4); graph.addEdge(0,6, 4); graph.addEdge(1,2, 5); graph.addEdge(1,3, 10); graph.addEdge(1,6, 9); graph.addEdge(3,4, 8); graph.addEdge(3,5, 8); graph.addEdge(3,6, 5); graph.addEdge(5,4, 5); graph.addEdge(5,6, 7); return graph; }//demo2 }//class
47
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
import java.util.Comparator; public class WeightedEdge implements Comparable { int v1; int v2; int weight; public WeightedEdge(int newV1, int newV2, int newWeight){ weight = newWeight; v1= newV1; v2= newV2; } public WeightedEdge (){ v1 = 0; v2 = 0; weight = 0; public int getV1() { return v1; public void setV1(int v1) { this.v1 = v1; public int getV2() { return v2; public void setV2(int v2) { this.v2 = v2; public int getWeight() { return weight; public void setWeight(int weight) { this.weight = weight; public String showData(){ return String.format(" [v%d, v%d, W:%d]", v1, v2, weight); @Override public int compareTo(Object otherEdge) { // compare object's weights WeightedEdge other = (WeightedEdge)otherEdge; if ( this.weight == other.weight ) return 0; else if ( this.weight > other.weight ) return 1; else return -1;
48
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
package csu.matos; import java.util.ArrayList; import java.util.PriorityQueue; public class DirectedGraph<E> { private ArrayList<E> vertices; private ArrayList<PriorityQueue<WeightedEdge>> neighbors; private boolean isDirected = true; public boolean isDirected() { return isDirected; } public void setDirected(boolean isDirected) { this.isDirected = isDirected; private ArrayList<Integer> costs; private ArrayList<WeightedEdge> solutionEdges; private ArrayList<Integer> solutionVertices; private final int INFINITE = Integer.MAX_VALUE; // //////////////////////////////////////////////////////////////// public DirectedGraph() { vertices = new ArrayList<E>(); neighbors = new ArrayList<PriorityQueue<WeightedEdge>>(); // ////////////////////////////////////////////////////////////// public void addVertice(E newVertice) { vertices.add(newVertice); neighbors.add(new PriorityQueue<WeightedEdge>()); public WeightedEdge addEdge(int v1, int v2, int newWeight) { WeightedEdge e = new WeightedEdge(v1, v2, newWeight); PriorityQueue<WeightedEdge> adjacent = neighbors.get(v1); if (!adjacent.contains(e)) neighbors.get(v1).add(e); // undirected graphs have bi-directional edges if (!isDirected){ WeightedEdge e2 = new WeightedEdge(v2, v1, newWeight); PriorityQueue<WeightedEdge> adjacent2 = neighbors.get(v2); if (!adjacent.contains(e2)) neighbors.get(v2).add(e2); return e;
49
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
// //////////////////////////////////////////////////////////////////// public void showData() { System.out.printf("\n<<< Graph >>>"); for (int i = 0; i < vertices.size(); i++) { System.out.printf("\nVertice[%d]= %s", i, vertices.get(i)); } System.out.printf("\nneighbors[%d] >> ", i); PriorityQueue<WeightedEdge> adjacent = neighbors.get(i); for (WeightedEdge e : adjacent) { System.out.printf(" %s", e.showData()); try { System.out.printf("\nSolution Edges >>>"); for (int i = 0; i < solutionEdges.size(); i++) { if (solutionEdges.get(i) == null) System.out.printf(" %s", "null"); else System.out.printf(" %s", solutionEdges.get(i).showData()); } catch (Exception e) { }// showData public void showCosts() { if (solutionVertices != null) { System.out.printf("\nSolution Vertices >>> "); for (Integer v : solutionVertices) { System.out.printf(" v%d ", v); if (costs != null) { System.out.printf("\nCosts >>>"); if (costs.get(i) == INFINITE) System.out.printf(" costs[%d]= INFINITE", i); System.out.printf(" costs[%d]= %s", i, costs.get(i));
50
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
// ///////////////////////////////////////////////////////////////////// public void minimumDistance(int sourceVertex) { solutionVertices = new ArrayList<Integer>(); solutionEdges = new ArrayList<WeightedEdge>(); // initialize the cost matrix (INFINITE all cells) // initialize solutionEdges with an edge from the // ancestor node to the current node (all null for now) costs = new ArrayList<Integer>(vertices.size()); for (int i = 0; i < vertices.size(); i++) { costs.add(INFINITE); solutionEdges.add(null); } // add sourceVertex to solutionVertices solutionVertices.add(sourceVertex); // set initial cost to reach sourceVertex to zero costs.set(sourceVertex, 0); // prepare initial costs matrix based on source vertex alone adjustCostOfNodesAdjacentTo(sourceVertex); // find best next node to add to solution set // for each vertex v2 not in the solution but reachable // from a node in solutionVertices // adjust cost = MIN( costs[v2], costs[v1]+edge[v1,v2] ) int v1 = sourceVertex, v2 = sourceVertex, w12 = 0; while (solutionVertices.size() < vertices.size()) { // choose v1 not in solutionVertices such costs[v1] is a minimum v1 = closestNodeNotYetInSolution(solutionVertices); // add node v1 to solution set solutionVertices.add(v1); // adjust cost to each node v2 not in the solution but reachable // from v1 adjustCostOfNodesAdjacentTo(v1); showCosts(); }// minimumDistance
51
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
// ////////////////////////////////////////////////////////////////////////////// private void adjustCostOfNodesAdjacentTo(int v1) { int v2, w12; PriorityQueue<WeightedEdge> adjacent = neighbors.get(v1); for (WeightedEdge e : adjacent) { v2 = e.getV2(); w12 = e.getWeight(); if (costs.get(v2) > costs.get(v1) + w12) { costs.set(v2, costs.get(v1) + w12); solutionEdges.set(v2, e); System.out.printf("\nMIN %d Best Edge %s", w12, e.showData()); }// if }// for }// adjustCostOfNodesAdjacentTo private int closestNodeNotYetInSolution(ArrayList<Integer> solutionVertices) { int minimum = INFINITE; int nodeIndex = 0; for (int i = 0; i < vertices.size(); i++) { if (!solutionVertices.contains(i) && (costs.get(i) < minimum)) { minimum = costs.get(i); nodeIndex = i; } return nodeIndex; }// closestNodeNotYetInSolution }// class
52
Appendix B. Dijkstra Shortest Path Between Graph Nodes (Single Source)
CONSOLE OUTPUT Minumum Distance - Dijkstra - Sourve: v0>>> MIN 2 Best Edge [v0, v1, W:2] MIN 10 Best Edge [v0, v4, W:10] MIN 3 Best Edge [v1, v2, W:3] MIN 7 Best Edge [v1, v4, W:7] Solution Vertices >>> v0 v1 Costs >>> costs[0]= 0 costs[1]= 2 costs[2]= 5 costs[3]= INFINITE costs[4]= 9 MIN 4 Best Edge [v2, v3, W:4] Solution Vertices >>> v0 v1 v2 Costs >>> costs[0]= 0 costs[1]= 2 costs[2]= 5 costs[3]= 9 costs[4]= 9 Solution Vertices >>> v0 v1 v2 v3 Solution Vertices >>> v0 v1 v2 v3 v4 <<< Graph >>> Vertice[0]= V0 Vertice[1]= V1 Vertice[2]= V2 Vertice[3]= V3 Vertice[4]= V4 neighbors[0] >> [v0, v1, W:2] [v0, v4, W:10] neighbors[1] >> [v1, v2, W:3] [v1, v4, W:7] neighbors[2] >> [v2, v3, W:4] neighbors[3] >> [v3, v4, W:5] neighbors[4] >> [v4, v2, W:6] Solution Edges >>> null [v0, v1, W:2] [v1, v2, W:3] [v2, v3, W:4] [v1, v4, W:7]
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.