Question: I have problems with prims method and dijkstras method in GraphAlgorithms.java. public class GraphAlgorithms { /** * Finds the single-source shortest distance between the start
I have problems with prims method and dijkstras method in GraphAlgorithms.java.
public class GraphAlgorithms { /** * Finds the single-source shortest distance between the start vertex and * all vertices given a weighted graph (you may assume non-negative edge * weights). * * Return a map of the shortest distances such that the key of each entry * is a node in the graph and the value for the key is the shortest distance * to that node from start, or Integer.MAX_VALUE (representing infinity) * if no path exists. * * You may import/use {@code java.util.PriorityQueue}, * {@code java.util.Map}, and {@code java.util.Set} and any class that * implements the aforementioned interfaces, as long as it's efficient. * * You should implement the version of Dijkstra's where you terminate the * algorithm once either all vertices have been visited or the PQ becomes * empty. * * DO NOT modify the structure of the graph. The graph should be unmodified * after this method terminates. * * @throws IllegalArgumentException if any input is null, or if start * doesn't exist in the graph. * @param the generic typing of the data * @param start index representing which vertex to start at (source) * @param graph the graph we are applying Dijkstra's to * @return a map of the shortest distances from start to every other node * in the graph */ public static Map, Integer> dijkstras(Vertex start, Graph graph) { if (start == null || graph == null) { throw new IllegalArgumentException("Inputs cannot be null."); } if (!graph.getAdjList().containsKey(start)) { throw new IllegalArgumentException("Vertax does not exist."); } PriorityQueue> pq = new PriorityQueue<>(); Set visited = new HashSet<>(); Map, List>> adjList = graph.getAdjList(); Map, Integer> dijkstra = new HashMap<>(); for (Vertex v : adjList.keySet()) { dijkstra.put(v, Integer.MAX_VALUE); } dijkstra.put(start, 0); //pq.add(new Edge(start, 0)); while (!pq.isEmpty()) { Edge curr = pq.poll(); List> vdpairs = graph.getAdjList().get(curr.getV()); for (Edge vdp : vdpairs) { int distance = curr.getWeight() + vdp.getWeight(); if (distance < dijkstra.get(vdp.getV())) { dijkstra.put(vdp.getV(), distance); //pq.add(new Edge(distance)); } } } return dijkstra; } /** * Runs Prim's algorithm on the given graph and return the Minimal * Spanning Tree (MST) in the form of a set of Edges. If the graph is * disconnected and therefore no valid MST exists, return null. * * You may assume that the passed in graph is undirected. In this framework, * this means that if (u, v, 3) is in the graph, then the opposite edge * (v, u, 3) will also be in the graph, though as a separate Edge object. * * The returned set of edges should form an undirected graph. This means * that every time you add an edge to your return set, you should add the * opposite edge to the set as well. This is for testing purposes. * * You may assume that there will only be one valid MST that can be formed. * * You should NOT allow self-loops into the MST. * * You may import/use {@code java.util.PriorityQueue}, * {@code java.util.Set}, and any class that implements the aforementioned * interface, as long as it's efficient. * * The only instance of {@code java.util.Map} that you may use is the * adjacency list from {@code graph}. DO NOT create new instances of Map * for this method (storing the adjacency list in a variable is fine). * * DO NOT modify the structure of the graph. The graph should be unmodified * after this method terminates. * * @throws IllegalArgumentException if any input * is null, or if {@code start} doesn't exist in the graph * @param the generic typing of the data * @param start the vertex to begin Prims on * @param graph the graph we are applying Prims to * @return the MST of the graph or null if there is no valid MST */ public static Set> prims(Vertex start, Graph graph) { if (start == null || graph == null) { throw new IllegalArgumentException("Inputs cannot be null."); } if (!graph.getAdjList().containsKey(start)) { throw new IllegalArgumentException("Vertax does not exist."); } Set> visited = new HashSet<>(); Set> mst = new HashSet<>(); Map, List>> adjList = graph.getAdjList(); PriorityQueue> pq = new PriorityQueue<>(); Vertex curr = start; while (mst.size() != adjList.size() - 1) { List> list = adjList.get(curr); for (Edge vdp : list) { Vertex v = vdp.getV(); if (!visited.contains(v)) { pq.add(new Edge<>(curr, v, vdp.getWeight())); } } if (!pq.isEmpty()) { Edge currE = pq.remove(); mst.add(currE); visited.add(currE.getU()); visited.add(currE.getV()); curr = currE.getV(); } } return mst; } } .
.
public class Edgeimplements Comparable super T>> { private Vertex u; private Vertex v; private int weight; /** * Creates a directed edge from vertex u to vertex v. Any single edge is * always directed, so if you're trying to create an undirected edge, you * must create the edges (u, v, weight) and (v, u, weight) when creating the * graph. * * @param u the start vertex of the edge * @param v the end vertex of the edge * @param weight the weight value of the edge * @throws IllegalArgumentException if any of the arguments are null */ public Edge(Vertex u, Vertex v, int weight) { if (u == null || v == null) { throw new IllegalArgumentException("Arguments cannot be null."); } this.u = u; this.v = v; this.weight = weight; } @Override public int hashCode() { return u.hashCode() ^ v.hashCode() ^ weight; } @Override public boolean equals(Object o) { if (o != null && o instanceof Edge>) { edgeno numeric noise key o; return weight == e.weight && u.equals(e.u) && v.equals(e.v); } else { return false; } } @Override public int compareTo(Edge super T> e) { return weight - e.getWeight(); } /** * Gets the weight of this edge. * * @return the weight of this edge */ public int getWeight() { return weight; } /** * Gets u, the starting vertex of this edge. * * @return the u vertex of this edge */ public Vertex getU() { return u; } /** * Gets v, the ending vertex of this edge. * * @return the v vertex of this edge */ public Vertex getV() { return v; } @Override public String toString() { return "Edge from " + u + " to " + v + " with weight " + weight; } }
.
.
public class Graph{ private Set > vertices; private Set > edges; private Map , List >> adjList; /** * Builds the graph from a set of vertices and an edge list. All edges in * the edge set are assumed to be directed, so if you want to create an * undirected edge, the edge set must contain both the forward and backwards * edges. * * @param vertices the vertex set * @param edges the edge set * @throws IllegalArgumentException if any of the arguments are null or if * the vertex set doesn't contain all of the vertices. */ public Graph(Set > vertices, Set > edges) { if (vertices == null || edges == null) { throw new IllegalArgumentException("Arguments cannot be null."); } this.vertices = new HashSet<>(vertices); this.edges = new HashSet<>(edges); adjList = new HashMap<>(); for (Vertex v : vertices) { adjList.put(v, new ArrayList<>()); } for (Edge e : edges) { if (adjList.containsKey(e.getU())) { adjList.get(e.getU()).add(e); } else { throw new IllegalArgumentException("Vertex set must contain all" + "vertices of the graph."); } } } /** * Gets the vertex set of this graph. * * @return the vertex set of this graph */ public Set > getVertices() { return vertices; } /** * Gets the edge set of this graph. * * @return the edge set of this graph */ public Set > getEdges() { return edges; } /** * Gets the adjacency list of this graph. * * @return the adjacency list of this graph */ public Map , List >> getAdjList() { return adjList; } }
.
.
public class Vertex{ private T data; /** * Creates a Vertex object holding the given data. * * @param data the object that is stored in this Vertex * @throws IllegalArgumentException if data is null */ public Vertex(T data) { if (data == null) { throw new IllegalArgumentException("Data cannot be null."); } this.data = data; } @Override public boolean equals(Object o) { if (o != null && o instanceof Vertex) { return data.equals(((Vertex>) o).data); } else { return false; } } @Override public int hashCode() { return data.hashCode(); } /** * Gets the data in this vertex. * * @return the data in this vertex */ public T getData() { return data; } @Override public String toString() { return data.toString(); } }
.
.
public class GraphAlgorithmsStudentTests { private Graph directedGraph; private Graph undirectedGraph; @Before public void init() { directedGraph = createDirectedGraph(); undirectedGraph = createUndirectedGraph(); } /** * Creates a directed graph. * The graph is depicted in the pdf. * * @return the completed graph */ private Graph createDirectedGraph() { Set> vertices = new HashSet>(); for (int i = 1; i <= 7; i++) { vertices.add(new Vertex(i)); } Set> edges = new HashSet>(); edges.add(new Edge<>(new Vertex<>(1), new Vertex<>(2), 0)); edges.add(new Edge<>(new Vertex<>(1), new Vertex<>(3), 0)); edges.add(new Edge<>(new Vertex<>(1), new Vertex<>(4), 0)); edges.add(new Edge<>(new Vertex<>(3), new Vertex<>(5), 0)); edges.add(new Edge<>(new Vertex<>(4), new Vertex<>(6), 0)); edges.add(new Edge<>(new Vertex<>(5), new Vertex<>(4), 0)); edges.add(new Edge<>(new Vertex<>(5), new Vertex<>(7), 0)); edges.add(new Edge<>(new Vertex<>(7), new Vertex<>(6), 0)); return new Graph(vertices, edges); } /** * Creates an undirected graph. * The graph is depicted in the pdf. * * @return the completed graph */ private Graph createUndirectedGraph() { Set> vertices = new HashSet<>(); for (int i = 65; i <= 70; i++) { vertices.add(new Vertex((char) i)); } Set> edges = new HashSet<>(); edges.add(new Edge<>(new Vertex<>('A'), new Vertex<>('B'), 7)); edges.add(new Edge<>(new Vertex<>('B'), new Vertex<>('A'), 7)); edges.add(new Edge<>(new Vertex<>('A'), new Vertex<>('C'), 5)); edges.add(new Edge<>(new Vertex<>('C'), new Vertex<>('A'), 5)); edges.add(new Edge<>(new Vertex<>('C'), new Vertex<>('D'), 2)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('C'), 2)); edges.add(new Edge<>(new Vertex<>('A'), new Vertex<>('D'), 4)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('A'), 4)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('E'), 1)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('D'), 1)); edges.add(new Edge<>(new Vertex<>('B'), new Vertex<>('E'), 3)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('B'), 3)); edges.add(new Edge<>(new Vertex<>('B'), new Vertex<>('F'), 8)); edges.add(new Edge<>(new Vertex<>('F'), new Vertex<>('B'), 8)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('F'), 6)); edges.add(new Edge<>(new Vertex<>('F'), new Vertex<>('E'), 6)); return new Graph(vertices, edges); } @Test public void testDijkstras() { Map, Integer> dijkActual = GraphAlgorithms.dijkstras( new Vertex('D'), undirectedGraph); Map, Integer> dijkExpected = new HashMap<>(); dijkExpected.put(new Vertex<>('A'), 4); dijkExpected.put(new Vertex<>('B'), 4); dijkExpected.put(new Vertex<>('C'), 2); dijkExpected.put(new Vertex<>('D'), 0); dijkExpected.put(new Vertex<>('E'), 1); dijkExpected.put(new Vertex<>('F'), 7); assertEquals(dijkExpected, dijkActual); } @Test public void testPrims() { Set> mstActual = GraphAlgorithms.prims( new Vertex('D'), undirectedGraph); Set> edges = new HashSet<>(); edges.add(new Edge<>(new Vertex<>('C'), new Vertex<>('D'), 2)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('C'), 2)); edges.add(new Edge<>(new Vertex<>('A'), new Vertex<>('D'), 4)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('A'), 4)); edges.add(new Edge<>(new Vertex<>('D'), new Vertex<>('E'), 1)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('D'), 1)); edges.add(new Edge<>(new Vertex<>('B'), new Vertex<>('E'), 3)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('B'), 3)); edges.add(new Edge<>(new Vertex<>('E'), new Vertex<>('F'), 6)); edges.add(new Edge<>(new Vertex<>('F'), new Vertex<>('E'), 6)); assertEquals(edges, mstActual); } }
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
