Пример #1
0
        public static Graph buildTree()
        {
            Node n = new Node(0);
            Graph graph = new Graph(n);
            graph.root = n;
            graph.root.key = 0;
            Node n1 = new Node(1);
            Node n2 = new Node(2);
            Node n3 = new Node(3);
            Node n4 = new Node(4);
            Node n5 = new Node(5);
            Node n6 = new Node(6);
            Node n7 = new Node(7);
            Node n8 = new Node(8);

            graph.AddEdge(n, n1, 4);
            graph.AddEdge(n, n7, 8);

            graph.AddEdge(n1, n, 4);
            graph.AddEdge(n1, n7, 11);
            graph.AddEdge(n1, n2, 8);

            graph.AddEdge(n2, n1, 8);
            graph.AddEdge(n2, n8, 2);
            graph.AddEdge(n2, n3, 7);
            graph.AddEdge(n2, n5, 4);

            graph.AddEdge(n3, n2, 7);
            graph.AddEdge(n3, n5, 14);
            graph.AddEdge(n3, n4, 9);

            graph.AddEdge(n7, n, 8);
            graph.AddEdge(n7, n1, 11);
            graph.AddEdge(n7, n8, 7);
            graph.AddEdge(n7, n6, 1);

            graph.AddEdge(n4, n3, 9);
            graph.AddEdge(n4, n5, 10);

            graph.AddEdge(n5, n2, 4);
            graph.AddEdge(n5, n6, 2);
            graph.AddEdge(n5, n3, 14);
            graph.AddEdge(n5, n4, 10);

            graph.AddEdge(n6, n7, 1);
            graph.AddEdge(n6, n8, 6);
            graph.AddEdge(n6, n5, 2);

            graph.AddEdge(n8, n7, 7);
            graph.AddEdge(n8, n2, 2);
            graph.AddEdge(n8, n6, 6);

            return graph;
        }
Пример #2
0
        public Graph Prims()
        {
            Graph mst = new Graph(null);
            List<Node> temp = new List<Node>();
            Node cur;
            heapify(nodeset);

            while (nodeset.Count > 0)
            {
                cur = nodeset[0];   //extract min
                nodeset.RemoveAt(0);
                temp.Add(cur);
                Node n = new Node(cur.data);
                if (cur.parent != null)
                {
                    mst.AddEdge(cur.parent, n, cur.key);
                    cur.parent = null;
                }
                else
                {
                    mst.nodeset.Add(n);
                    mst.root = n;
                }

                foreach (KeyValuePair<Node, int> kv in cur.edgesTo)
                {
                    if (kv.Key.key > kv.Value)
                    {
                        kv.Key.key = kv.Value;
                        kv.Key.parent = n;
                    }
                }
                heapify(nodeset);
                //siftDown(nodeset, 0, nodeset.Count - 1);
            }
            this.nodeset = temp;
            return mst;
        }