最小生成樹__Kurskal演算法

何畢之發表於2018-06-19
using System;
using System.Collections.Generic;
using System.Linq;

namespace 最小生成樹__Kurskal演算法
{
    class Program
    {
        public static readonly int M = 999999;//表示不可到達距離  
        static int[,] map = new int[,] {
                { 0, 23, M, M,M,28,36 },
                { 23, 0, 20, M,M,M,1 },
                { M,20,0,15,M,M,4 },
                { M,M,15,0,3,M,9 },
                { M,M,M,3,0,17,16},
                { 28,M,M,M,17,0,25 },
                { 36,1,4,9,16,25,0 }
            };//路徑圖  
        public class Edge
        {
            public int Start { get; set; }//邊的起點
            public int End { get; set; }//邊的終點
            public int Weight { get; set; }//長度

            public Edge(int s, int e, int w)
            {
                Start = s;
                End = e;
                Weight = w;
            }
        }
        public static  int N = (int)Math.Sqrt(map.Length);//獲取地點數;   
        public static int[] Nodes = new int[N];
        public static List<Edge> Edges = new List<Edge>();
        public static List<Edge> edges = new List<Edge>();

        static void Main(string[] args)
        {
            for (int i = 0; i < N; i++)
            {
                Nodes[i] = i;
            }

            //轉化每條邊為Edge型別 並新增近列表
            for (int i = 0; i < N - 1; i++)
            {
                for (int j = i + 1; j < N; j++)
                {
                    if (map[i, j] != M)
                    {
                        Edge edge = new Edge(i, j, map[i, j]);
                        Edges.Add(edge);
                    }
                }
            }
            //對邊按權重大小排序 升序
            var E =
                from v in Edges
                orderby v.Weight
                select v;

            //對每條邊進行判定
            foreach (var edge in E)
            {
                if (Merge(edge.Start, edge.End))
                    edges.Add(edge);//將符合條件的邊新增進邊的集合 用於輸出
            }


            //輸出結果
            int sum = 0;
            foreach (var e in edges)
            {
                sum += e.Weight;
                Console.WriteLine("邊的起點:" + (e.Start + 1) + ";邊的終點:" + (e.End + 1) + ";邊的權重:" + e.Weight);
            }

            Console.WriteLine("邊的總權重:" + sum);

            Console.ReadKey();
        }
        /// <summary>
        /// 對邊的起點進行判定 
        /// 若相等則返回False 表示這條邊不符合最小生成樹要求
        /// 若不想等 則將所有執行並集操作
        /// 即將所有與此邊終點相等的邊的值變成此邊的起點值
        /// </summary>
        /// <param name="a">邊的起點</param>
        /// <param name="b">邊的終點</param>
        /// <returns></returns>
        static bool Merge(int a,int b)
        {
            int p = Nodes[a];
            int q = Nodes[b];
            if (p == q) return false;
            for(int i = 0; i < N; i++)
            {
                if (Nodes[i] == q)
                    Nodes[i] = p;
            }
            return true;
        }
    }

}




相關文章