Exemplo n.º 1
0
        private static Graph buildgraph()
        {
            gNode n0 = new gNode(0);
            gNode n1 = new gNode(1);
            gNode n2 = new gNode(2);
            gNode n3 = new gNode(3);
            gNode n4 = new gNode(4);
            gNode n5 = new gNode(5);
            gNode n6 = new gNode(6);
            gNode n7 = new gNode(7);
            gNode n8 = new gNode(8);

            Graph graph = new Graph(n0);
            graph.AddEdge(n0, n1, 4);
            graph.AddEdge(n0, n7, 8);
            graph.AddEdge(n1, n7, 11);
            graph.AddEdge(n1, n2, 9);
            graph.AddEdge(n2, n8, 2);
            graph.AddEdge(n7, n8, 7);
            graph.AddEdge(n7, n6, 1);
            graph.AddEdge(n8, n6, 6);
            graph.AddEdge(n6, n5, 2);
            graph.AddEdge(n5, n2, 4);
            graph.AddEdge(n2, n3, 7);
            graph.AddEdge(n3, n5, 14);
            graph.AddEdge(n5, n4, 10);
            graph.AddEdge(n3, n4, 9);

            return graph;
        }
Exemplo n.º 2
0
        public Graph Prims()
        {
            Graph minSpan = new Graph(null);
            List<gNode> temp = new List<gNode>();
            while (nodeList.Count > 0)
            {

                Heapify();  //place graph in min heap
                gNode root = nodeList[0];   //extract node with min key
                gNode n = new gNode(root.data);

                if (root.parent != null)
                {
                    if (minSpan.start == null)
                        minSpan.start = root.parent;

                    minSpan.AddEdge(root.parent, n, root.key);
                    root.parent = null;
                }

                for (int i = 0; i < root.adj.Count; i++)
                {
                    if (root.adj[i].key > root.cost[i])
                    {
                        root.adj[i].key = root.cost[i];
                        root.adj[i].parent = n;
                    }
                }

                temp.Add(root);
                nodeList.RemoveAt(0);
            }

            nodeList = temp;
            return minSpan;
        }