package graphs; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class WeightedGraph { private int numVertices; private int numDirectedEdges; private Bag[] adj; //<-- bag of EDGES instead of vertices // adj[i] contains all of the edges incident to i public WeightedGraph(int numVertices) { initializeEmptyGraph(numVertices); } public String toString() { StringBuilder sb = new StringBuilder(); String NEWLINE = System.getProperty("line.separator"); sb.append(numVertices + " vertices, " + numDirectedEdges + " edges " + NEWLINE); for (int v = 0; v < numVertices; v++) { sb.append(v + ": "); for (Edge w : adj[v]) { sb.append(w + " "); } sb.append(NEWLINE); } return sb.toString(); } // create graph from a file public WeightedGraph(String pathToFile) { File f = new File(pathToFile); Scanner scanner; try { scanner = new Scanner(f); // read number of vertices int numVertices = Integer.parseInt(scanner.nextLine()); initializeEmptyGraph(numVertices); while (scanner.hasNextLine()) { // read and add edges int from = scanner.nextInt(); int to = scanner.nextInt(); double weight = scanner.nextDouble(); Edge e = new Edge(from, to, weight); this.addEdge(e); } } catch (FileNotFoundException e) { e.printStackTrace(); } } private void initializeEmptyGraph(int numVertices) { this.numVertices = numVertices; adj = (Bag[]) new Bag[numVertices]; // <-- the necessary, ugly cast for (int v = 0; v < numVertices; v++) { adj[v] = new BagArray(); } } public void addEdge(Edge e) { int v = e.either(); int w = e.other(v); adj[v].add(e); // <-- add edge to adjacency list adj[w].add(e); numDirectedEdges++; } public Iterable adj(int v) { return adj[v]; } public int numVertices() { return numVertices; } public int numDirectedEdges() { return numDirectedEdges; } public static void main(String[] args) { WeightedGraph g = new WeightedGraph("/Users/pauloser/Desktop/tinyEWG.txt"); System.out.println(g); } }