我正在尝试用Java实现Prim的算法,使用我的图表HashMap+LinkedList和一个包含连接顶点和权重的类边:
adjacencyList = new HashMap>>();
我的想法是,从一个给定的顶点开始:
1) 将所有顶点保存到LinkedList中,以便每次访问它们时都可以将其删除
3) 使用PriorityQueue查找最小权重
我很困惑如何返回MST和我的代码上有几个错误,我不知道如何修复它们!
Prim.java:21: error: no suitable method found for addAll(LinkedList>)
unvisited.addAll(graph.getVertices());
^
method Collection.addAll(Collection extends T>) is not applicable
(argument mismatch; LinkedList> cannot be converted to Collection extends T>)
method List.addAll(Collection extends T>) is not applicable
(argument mismatch; LinkedList> cannot be converted to Collection extends T>)
method AbstractCollection.addAll(Collection extends T>) is not applicable
(argument mismatch; LinkedList> cannot be converted to Collection extends T>)
method LinkedList.addAll(Collection extends T>) is not applicable
(argument mismatch; LinkedList> cannot be converted to Collection extends T>)
where T is a type-variable: T extends Comparable declared in class Prim
问题似乎出在我的getVertices()方法(它返回图的所有顶点)中,因为它返回
Set
;我尝试使用addAll和get-as将所有内容都放入LinkedList中并返回此LinkedList,但它也给出了相同的错误。我做错什么了?
public class Graph> {
.
.
public Set getVertices() {
if (adjacencyList.isEmpty()) {
System.out.println("Error message.\n");
return null;
} else
return adjacencyList.keySet();
}
}
第二个错误是:
Prim.java:28: error: incompatible types: T cannot be converted to Edge
for (Edge edge : graph.getAdjacentVertices(source)) {
^
where T is a type-variable:
T extends Comparable declared in class Prim
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
Edge
到
source
普里姆:
public class Prim> {
public minimumSpanningTree(Graph> graph, T vertex) {
//ArgumentException
double weight = 0;
T source = vertex;
LinkedList vertexSet = new LinkedList<>();
LinkedList> path = new LinkedList<>();
vertexSet.addAll(graph.getVertices()); //unvisited ERROR HERE
vertexSet.remove(source);
double numberOfVertices = graph.getVertices().size();
PriorityQueue> priorityQueue = new PriorityQueue<>();
while (!vertexSet.isEmpty()) {
for (Edge edge : graph.getAdjacentVertices(source)) {//ERROR
if (vertexSet.contains(edge.getDestination()))
priorityQueue.insert(edge);
}
Edge minWeight = priorityQueue.extractMin();
weight += minWeight.getWeight();
path.add(HERE I SHOULD PUT MST PATH BUT I DON'T KNOW HOW!!);
source = minWeight.getDestination();
vertexSet.remove(source);
}
return ;
}
}
我也不知道如何在MST中找到边的数量;我是否应该为每个顶点(HashMap的键集)找到LinkedList的大小(这是它的值)并对它们进行求和?
编辑:getAdjacentVertices方法
public LinkedList getAdjacentVertices(T vertex) {
if (adjacencyList.isEmpty() || adjacencyList.containsKey(vertex) == false) {
System.out.println("Error msg.\n");
return null;
} else {
LinkedList allAdjacents = new LinkedList<>();
for (Edge edge : adjacencyList.get(vertex)) {
allAdjacents.add(edge.getDestination());
}
return allAdjacents;
}
}