# Prim和Kruskal算法

## Prim和Kruskal算法

class Vertex {
String name;// 顶点名称
Edge next;// 下一条边（第一个为顶点 后面都是边）

public Vertex(String name) {
this.name = name;
}

// 获取结点的出边
public TreeSet<Edge> outEdges() {
TreeSet<Edge> treeSet = new TreeSet<>();
Edge edge = this.next;
while (edge != null) {
edge = edge.next;
}
//Collections.sort(treeSet);
return treeSet;
}

@Override
public String toString() {
return "Vertex [name=" + name + "]";
}

}


class Edge implements Comparable<Edge>{
String name;// 指向的顶点名称
int weight;// 权值
Edge next;// 下一条边（链表上）

public Edge(String name, int weight) {
this.name = name;
this.weight = weight;
}

@Override
public String toString() {
return "Edge [name=" + name + ", weight=" + weight + "]";
}

@Override
public int compareTo(Edge o) {
if(this.weight!=o.weight)
return this.weight-o.weight;
else
return this.name.compareTo(o.name);
}
}


Prim算法

/**
* 普利姆算法
* @param name 开始结点
* @return
*/
public Set<Edge> prim(String name) {
Vertex beginVertex = vertexMap.get(name);
if (beginVertex.next == null)
return null;
TreeSet<Edge> treeSet = new TreeSet<>(beginVertex.outEdges());
Edge edge = treeSet.pollFirst();
}
}


Kruskal算法

public Set<Edge> kruskal(){
TreeSet<Edge> allEdges = getAllEdges();
int size=vertexMap.size()-1;
if(size==-1) return null;
UnionFind<Vertex> uf = new UnionFind<>();
Iterator<Vertex> it = vertexMap.values().iterator();
while(it.hasNext()) {
uf.makeSet(it.next());
}
Edge edge = allEdges.pollFirst();
if(uf.isSame(vertexMap.get(edge.beginName), vertexMap.get(edge.endName))) continue;
uf.union(vertexMap.get(edge.beginName), vertexMap.get(edge.endName));
}