import java.util.*; /** This class represents undirected, weighted graphs. An inner class Edge represents edges in a suitable form for entry into an instance of a collection class */ // An adjacency matrix representation is used. Methods // include those for finding a minimum-cost spanning // tree using Kruskal's algorithm, and for finding // an approximate TSP solution. In both cases, // solutions are represented by Vectors of Edges, // although formally Lists are returned. public class UndirectedGraph { /** the adjacency matrix */ protected int[][] adjacency; /** the number of vertices in the graph */ protected int NUM_VERTICES; /** builds an undirected graph with n vertices and no edges @param n the number of vertices desired */ public UndirectedGraph(int n) { NUM_VERTICES=n; adjacency=new int[n][n]; } /** builds an undirected graph with n vertices and random weights, uniformly distributed in the range from 1 through a given maximum weight @param n the number of vertices desired @param r the Random object to be used in computing the random weights @param maxCost the maximum weight */ // The adjacency matrix is filled in row major order, // except that since the graph is to be undirected, // only the entries above the main // only the elements above the main diagonal // are computed randomly. The main diagonal entries // are all zero, and the other entries are // computed by symmetry public UndirectedGraph(int n, Random r,int maxCost) { int c; // an edge cost NUM_VERTICES=n; adjacency=new int[n][n]; for (int i=0; iint. @ param v the vector of edges @ return the total cost */ public static int traverseEdgeList(List v, boolean isDetailWanted) { Edge e=null; int totalCost=0; Iterator it = v.iterator(); while (it.hasNext()) { e=(Edge) it.next(); totalCost+=e.getCost(); System.out.print(e.getSource()); System.out.print("<->"); System.out.print(e.getDest()); if (isDetailWanted) { System.out.print(", cost "); System.out.println(e.getCost()); } else System.out.print(" "); } System.out.print("total cost: "); System.out.println(totalCost); return totalCost; } /** an inner class for representing edges */ protected class Edge implements Comparable { int source; int dest; int cost; /** a basic edge constructor @param s the desired source vertex @param d the desired destination vertex @param c the desired cost */ public Edge(int s, int d, int c) { source=s; dest=d; cost=c; } /** @return the source vertex of an edge */ int getSource() { return source; } /** @return the destination vertex of an edge */ int getDest() { return dest; } /** @return the cost of an edge */ int getCost() { return cost; } /** the comparison method for edges -- it simply compares costs @param e the edge @return an integer with the conventional interpretation for compareTo(Object) */ public int compareTo(Object e) { int ecost=((Edge) e).getCost(); if (costecost) return 1; else return 0; } } // end Edge }