Java Reference
In-Depth Information
22 /** Construct a WeightedGraph for vertices 0, 1, 2 and edge list */
23 public WeightedGraph(List<V> vertices, List<WeightedEdge> edges) {
24 createWeightedGraph(vertices, edges);
25 }
26
27 /** Construct a WeightedGraph from vertices 0, 1, and edge array */
28 public WeightedGraph(List<WeightedEdge> edges,
29 int numberOfVertices) {
30 List<V> vertices = new ArrayList<>();
31 for ( int i = 0 ; i < numberOfVertices; i++)
32 vertices.add((V)( new Integer(i)));
33
34 createWeightedGraph(vertices, edges);
35 }
36
37
constructor
constructor
/** Create adjacency lists from edge arrays */
38
private void createWeightedGraph(List<V> vertices, int [][] edges) {
39
this .vertices = vertices;
40
41 for ( int i = 0 ; i < vertices.size(); i++) {
42 neighbors.add( new ArrayList<Edge>()); // Create a list for vertices
43 }
44
45
create list for vertices
for ( int i = 0 ; i < edges.length; i++) {
46
neighbors.get(edges[i][ 0 ]).add(
47
new WeightedEdge(edges[i][ 0 ], edges[i][ 1 ], edges[i][ 2 ]));
create a weighted edge
48 }
49 }
50
51
/** Create adjacency lists from edge lists */
52
private void createWeightedGraph(
53
List<V> vertices, List<WeightedEdge> edges) {
54
this .vertices = vertices;
55
56
for ( int i = 0 ; i < vertices.size(); i++) {
57
neighbors.add( new ArrayList<Edge>()); // Create a list for vertices
create list for vertices
58 }
59
60
for (WeightedEdge edge: edges) {
61
neighbors.get(edge.u).add(edge); // Add an edge into the list
62 }
63 }
64
65
/** Return the weight on the edge (u, v) */
66
public double getWeight( int u, int v) throws Exception {
print edges
67
for (Edge edge : neighbors.get(u)) {
68
if (edge.v == v) {
69
return ((WeightedEdge)edge).weight;
70 }
71 }
72
73
throw new Exception( "Edge does not exit" );
74 }
75
76 /** Display edges with weights */
77 public void printWeightedEdges() {
78 for ( int i = 0 ; i < getSize(); i++) {
79 System.out.print(getVertex(i) + " (" + i + "): " );
80 for (Edge edge : neighbors.get(i)) {
81 System.out.print( "(" + edge.u +
get edge weight
 
 
Search WWH ::




Custom Search