最小生成树__Prim算法

using System;

namespace 最小生成树__Prim算法
{
    class Program
    {
        public static readonly int M = 999999;//表示不可到达距离
        static int[,] map = new int[,] {
                { 0, 6, 3, M,M,M },
                { 6, 0, 2, 5,M,M },
                { 3, 2, 0, 3, 4, M },
                { M, 5, 3, 0, 2, 3 },
                { M,M, 4, 2, 0, 5 },
                { M,M,M, 3, 5, 0 }
            };//路径图  
        public static readonly int N = (int)Math.Sqrt(map.Length);//获取地点数; 
        static bool[] visited = new bool[N];//节点是否被访问
        static int[] closest = new int[N];//记录上一个节点位置
        static int[] lowcost = new int[N];//记录上一个节点与当前节点的权值
        static readonly int start = 0;//开始顶点

        static void Main(string[] args)
        {
            Prim();
            string str1 = "closest 里的值为:";
            string str2 = "lowcost 里的值为:";
            int sum = 0;
            for (int i = 0; i < N; i++)
            {
                str1 += closest[i] + "   ";
                str2 += lowcost[i] + "   ";
                sum += lowcost[i];
            }
            Console.WriteLine(str1);
            Console.WriteLine(str2);
            Console.WriteLine("最小权重和为:" + sum);
            Console.ReadKey();
        }

        static void Prim()
        {
            visited[start] = true;//初始化,集合U只有一个元素,即start
            for (int i = 0; i < N; i++)
            {
                if (i != start)//出start意外所有元素
                {
                    lowcost[i] = map[start, i];//start到其他边的权值
                    closest[i] = start;//设置改点的最临近点为start
                    visited[i] = false;//初始化除start以外其他元素不属于U集合
                }
                else
                    lowcost[i] = 0;
            }

            for (int i = 0; i < N; i++)
            {
                int temp = M;
                int t = start;
                for (int j = 0; j < N; j++)//在集合V-U中寻找距离集合U最近的顶点t
                {
                    if ((!visited[j]) && (lowcost[j] < temp))
                    {
                        t = j;
                        temp = lowcost[j];
                    }
                }
                if (t == start)
                    break;
                visited[t] = true;
                for (int j = 0; j < N; j++)
                {
                    if ((!visited[j]) && (map[t, j] < lowcost[j]))
                    {
                        lowcost[j] = map[t, j];
                        closest[j] = t;
                    }
                }
            }

        }
    }
}



猜你喜欢

转载自blog.csdn.net/HeBizhi1997/article/details/80734288