kruskal算法

public class KruskalTest {
    @Test
    public void test(){

        PriorityQueue<Edge> queue = new PriorityQueue<>();
        Graph g = Graph.build();
        for(Edge e : g.getEdges()){
            queue.offer(e);
        }
        Edge edge = null;
        UF uf = new UF(6);
        List<Edge> res = new ArrayList<>();
        while((edge = queue.poll())!=null){
            if(!uf.isConnected(edge.getFromVertex(), edge.getToVertex())){
                uf.union(edge.getFromVertex(), edge.getToVertex());
                res.add(edge);
                System.out.println(edge);
                //System.out.println(queue.size());
            }
        }
    }
}


public class Graph {
    private String[] vertexs;
    private Edge[] edges;

    public static Graph build() {
        Graph g = new Graph();
        g.vertexs = new String[] { "A", "B", "C", "D", "E", "F" };
        g.edges = new Edge[] { Edge.build(0, 1, 1), Edge.build(0, 2, 1), Edge.build(0, 5, 1), Edge.build(1, 2, 2),
                Edge.build(2, 3, 3), Edge.build(3, 4, 4), Edge.build(4, 5, 5)};
/*      g.edges = new Edge[] { Edge.build(0, 1, 80), Edge.build(0, 3, 100), Edge.build(0, 5, 20), Edge.build(1, 2, 90),
                Edge.build(2, 3, 10), Edge.build(2, 5, 70), Edge.build(3, 4, 60), Edge.build(4, 5, 40) };
*/      return g;
    }
    public Edge[] getEdges() {
        return edges;
    }
    public String[] getVertexs() {
        return vertexs;
    }
}


public class Edge implements Comparable<Edge>{
    private int fromVertex;
    private int toVertex;
    private int weight;
    public int getFromVertex() {
        return fromVertex;
    }
    public void setFromVertex(int fromVertex) {
        this.fromVertex = fromVertex;
    }
    public int getToVertex() {
        return toVertex;
    }
    public void setToVertex(int toVertex) {
        this.toVertex = toVertex;
    }
    public int getWeight() {
        return weight;
    }
    public void setWeight(int weight) {
        this.weight = weight;
    }
    public static Edge build(int from,int to,int weight){
        Edge e = new Edge();
        e.fromVertex = from;
        e.toVertex = to;
        e.weight = weight;
        return e;
    }
    @Override
    public String toString(){
        return JSON.toJSONString(this);
    }
    @Override
    public int compareTo(Edge edge) {
        return Integer.compare(this.weight, edge.weight);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值