Заранее прошу прощения, если этот код покажется вам длинным, но я все еще новичок в Java, и мне сложно реализовать алгоритм Прима. Когда я отправляю свой сценарий на vocareum, я получаю сообщение о неправильном MST. Я постоянно отслеживаю свой сценарий и не могу понять причину, по которой я получаю эту ошибку.
Если у кого-нибудь есть какие-либо советы, я буду очень признателен! Опять же, я все еще новичок и, возможно, здесь что-то упущено.
См. ниже часть 1 моего сценария (которая является частью задания, в котором мы должны писать ). Это файл GraphAlgorithms.java.
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
/**
* Your implementation of Prim's algorithm.
*/
public class GraphAlgorithms {
/**
* Runs Prim's algorithm on the given graph and returns the Minimum
* 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
* reverse edge to the set as well. This is for testing purposes. This
* reverse edge does not need to be the one from the graph itself; you can
* just make a new edge object representing the reverse edge.
*
* You may assume that there will only be one valid MST that can be formed.
*
* You should NOT allow self-loops or parallel edges in the MST.
*
* You may import/use java.util.PriorityQueue, java.util.Set, and any
* class that implements the aforementioned interface.
*
* DO NOT modify the structure of the graph. The graph should be unmodified
* after this method terminates.
*
* The only instance of java.util.Map that you may use is the adjacency
* list from graph. DO NOT create new instances of Map for this method
* (storing the adjacency list in a variable is fine).
*
* You may assume that the passed in start vertex and graph will not be null.
* You may assume that the start vertex exists 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
|| !graph.getAdjList().containsKey(start)) {
throw new IllegalArgumentException();
}
PriorityQueue queue = new PriorityQueue();
Set visited = new HashSet();
Set edgeset = new HashSet();
for (Edge edge : graph.getEdges()){
if (edge.getU() == start){
queue.add(edge);
}
}
visited.add(start);
while (!queue.isEmpty()) {
Edge temp = queue.remove();
if (!visited.contains(temp.getV())) {
edgeset.add(new Edge(temp.getU(), temp.getV(), temp.getWeight()));
visited.add(temp.getV());
for (Edge edge : graph.getEdges()) {
if (temp.getV() == edge.getU()) {
queue.add(edge);
}
}
}
}
if (edgeset.size() < graph.getVertices().size() - 1) {
return null;
}
return edgeset;
}
}
Следующие сценарии представляют собой классы, которые нам предоставляются и которые явно не следует изменять. В этом может возникнуть необходимость, а может и нет необходимости копаться слишком глубоко, поскольку в моем сценарии, приведенном выше, в настоящее время используются лишь некоторые из методов. Но я прикрепил их все для справки. Ниже находится файл Edge.java.
/**
* Class representing a directed edge from u to v.
*
* DO NOT EDIT THIS CLASS!!
*
* @author CS 1332 TAs
* @version 1.0
*/
public class Edge implements Comparable
Подробнее здесь: https://stackoverflow.com/questions/730 ... proper-mst
Почему алгоритм моего Прима не возвращает правильный MST? ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Алгоритм поиска для поиска k наименьших значений в списке (алгоритм выбора/задача)
Anonymous » » в форуме C++ - 0 Ответы
- 47 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Нужен другой алгоритм для моего кода итерации всех подстрок заданной строки
Anonymous » » в форуме C++ - 0 Ответы
- 6 Просмотры
-
Последнее сообщение Anonymous
-