|
| 1 | +package ca.mcmaster.chapter.four.graph.mstree; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileNotFoundException; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Scanner; |
| 9 | + |
| 10 | +import ca.mcmaster.chapter.one.bag.Bag; |
| 11 | +import ca.mcmaster.chapter.one.bag.ListBag; |
| 12 | + |
| 13 | +public class EdgeWeightedGraph { |
| 14 | + private final int V; //Number of vertex |
| 15 | + private int E; //Number of edge |
| 16 | + private final Bag<Edge>[] adj; //Create bag for saving edges of vertex |
| 17 | + @SuppressWarnings("unchecked") |
| 18 | + public EdgeWeightedGraph(int V){ |
| 19 | + this.V = V; |
| 20 | + this.E = 0; |
| 21 | + adj = new Bag[V]; |
| 22 | + for(int v = 0; v < V ; v++) adj[v] = new ListBag<>(); |
| 23 | + } |
| 24 | + @SuppressWarnings("unchecked") |
| 25 | + public EdgeWeightedGraph(FileInputStream in){ |
| 26 | + Scanner scanner = null; |
| 27 | + try { |
| 28 | + scanner = new Scanner(in); |
| 29 | + V = scanner.nextInt(); |
| 30 | + E = 0; |
| 31 | + int edgeNum = scanner.nextInt(); |
| 32 | + adj = new Bag[V]; |
| 33 | + for(int v = 0; v < V ; v++) adj[v] = new ListBag<>(); |
| 34 | + for(int e = 0; e < edgeNum; e++) addEdge(new Edge(scanner.nextInt(), scanner.nextInt(), scanner.nextDouble())); |
| 35 | + } finally{ |
| 36 | + scanner.close(); |
| 37 | + } |
| 38 | + } |
| 39 | + private void addEdge(Edge e){ |
| 40 | + int v = e.either(); |
| 41 | + int w = e.other(v); |
| 42 | + adj[v].add(e); |
| 43 | + adj[w].add(e); |
| 44 | + E++; |
| 45 | + } |
| 46 | + public int V(){ |
| 47 | + return this.V; |
| 48 | + } |
| 49 | + public int E(){ |
| 50 | + return this.E; |
| 51 | + } |
| 52 | + public Iterable<Edge> adj(int v){ |
| 53 | + return adj[v]; |
| 54 | + } |
| 55 | + public Iterable<Edge> edges(){ |
| 56 | + List<Edge> res = new ArrayList<Edge>(); |
| 57 | + for(int v = 0; v < V; v++) |
| 58 | + for(Edge e : adj[v]){ |
| 59 | + if(v > e.other(v)) res.add(e); |
| 60 | + } |
| 61 | + return res; |
| 62 | + } |
| 63 | + public static void main(String[] args) throws FileNotFoundException { |
| 64 | + FileInputStream is = new FileInputStream(new File("src/ca/mcmaster/chapter/four/graph/mstree/tinyEWG.txt")); |
| 65 | + EdgeWeightedGraph graph = new EdgeWeightedGraph(is); |
| 66 | + Iterable<Edge> edges = graph.edges(); |
| 67 | + for(Edge e : edges) |
| 68 | + System.out.println(e.toString()); |
| 69 | + System.out.println(graph.E); |
| 70 | + } |
| 71 | +} |
0 commit comments