栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

数据结构与算法-K算法实现最小生成树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

数据结构与算法-K算法实现最小生成树

好久没有更新了今天介绍图的最小生成树的算法 

K算法-在图中节点没有构成环的基础上找到最小的可以联通所有节点的边集即图的最小生成树

通过使用并查集的结构来实现,上代码

//一个人图中从一个点出发遍历到所有节点且经历的路径最短
//算法 K算法
//  
public class 生成最小生成树 {



    //并查集的实现-简单版本
    public static class MySets{
        public HashMap> setMap;
        public MySets() {

        }
        public MySets(List nodes){
            for (Node cur : nodes){
                List set = new ArrayList();
                set.add(cur);
                setMap.put(cur, set);
            }
        }
        //from点与to点是否在一个集合中
        public boolean isSameSet(Node from, Node to){
            List fromSet = setMap.get(from);
            List toSet = setMap.get(to);
            return fromSet == toSet;
        }

        //from和to合并一个集合中
        public void union(Node from, Node to){
            List fromSet = setMap.get(from);
            List toSet = setMap.get(to);
            for (Node toNode : toSet){
                fromSet.add(toNode);
                setMap.put(toNode, fromSet);
            }
        }
    }
    //定义一个比较器
    public static class EdgeCompartor implements Comparator{

        public int compare(Edge o1, Edge o2) {
            return o1.weight - o2.weight;
        }
    }
    //k-克鲁斯卡尔-算法-选最小边链接 形成不了环就继续选
    public static Set kruskalMST(Graph graph){
        MySets mySets = new MySets((List) graph.nodes.values());
        PriorityQueue priorityQueue = new PriorityQueue<>(new EdgeCompartor());
        for (Edge edge : graph.edges){
            priorityQueue.add(edge);
        }
        Set result = new HashSet();
        while (!priorityQueue.isEmpty()){
            Edge edge = priorityQueue.poll();
            if (!mySets.isSameSet(edge.from, edge.to)){
                result.add(edge);
                mySets.union(edge.from, edge.to);
            }
        }
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937115.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号