Question: Since T is implemented using a list in the getMinimumSpanningTree and getShortestPath methods in Listing 29.2 WeightedGraph.java, testing whether a vertex u is in T

Since T is implemented using a list in the getMinimumSpanningTree and getShortestPath methods in Listing 29.2 WeightedGraph.java, testing whether a vertex u is in T by invoking T.contains(u) takes O(n) time. Modify these two methods by introducing an array named isInT. Set isInT[u] to true when a vertex u is added to T. Testing whether a vertex u is in T can now be done in O(1) time. Write a test program using the following code, where graph1 is created from Figure 29.1.WeightedGraph graph1 = new WeightedGraph (edges, vertices); WeightedGraph .MST treel = graph1.getMinimumSpanningTree();

Listing

+ treel.getTotalWeight()); System.out.println("Total weight is " treel.printTree(); WeightedGraph .ShortestPathTree tree2 = graph1.getShortestPath(graph1.getIndex("Chicago"));

%3D tree2.printA11Paths (); 1 import java.util.*; 2 3 public class WeightedGraph extends

AbstractGraph { 4 /** Construct an empty */ public WeightedGraph() { /**

Construct a WeightedGraph from vertices and edged in arrays */ public WeightedGraph(V[]

vertices, int[][] edges) { 10 11 12 createWeightedGraph(java.util.Arrays.asList(vertices), edges); 13 /** Construct

a WeightedGraph from vertices and edges in list */ public WeightedGraph(int[][] edges,

WeightedGraph graph1 = new WeightedGraph (edges, vertices); WeightedGraph .MST treel = graph1.getMinimumSpanningTree(); + treel.getTotalWeight()); System.out.println("Total weight is " treel.printTree(); WeightedGraph .ShortestPathTree tree2 = graph1.getShortestPath(graph1.getIndex("Chicago")); %3D tree2.printA11Paths (); 1 import java.util.*; 2 3 public class WeightedGraph extends AbstractGraph { 4 /** Construct an empty */ public WeightedGraph() { /** Construct a WeightedGraph from vertices and edged in arrays */ public WeightedGraph(V[] vertices, int[][] edges) { 10 11 12 createWeightedGraph(java.util.Arrays.asList(vertices), edges); 13 /** Construct a WeightedGraph from vertices and edges in list */ public WeightedGraph(int[][] edges, int numberofVertices) { 14 15 16 17 18 19 20 21 List vertices = new ArrayList (); for (int i = 0; i < numberofVertices; i++) vertices.add((V) (new Integer(i))); createWeightedGraph(vertices, edges);

Step by Step Solution

3.37 Rating (150 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

Refer Listing 291 292 298 in chapter 29 from the textbook for complete code To search for a vertex u in T can be done in O1 time instead of On time by introducing a boolean array isInT Create a static ... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java Programming Questions!