Exemplo n.º 1
0
        public void MinimumSpanningTreePrim(VertexMST <T> root)
        {
            foreach (var vertex in vertices.OfType <VertexMST <T> >())
            {
                vertex.Key         = int.MaxValue;
                vertex.Predecessor = null;
            }
            root.Key = 0;
            var heap = new MinHeap <VertexMST <T> >(vertices.Count, vertices.OfType <VertexMST <T> >().ToArray());

            while (!heap.IsEmpty)
            {
                //had to call heapify before extract min since it's not a min heap anymore due to the change of keys
                //instead of decrease key
                heap.Heapify(0);
                var min = heap.Extract();
                foreach (var edge in edges.Where((e) => e.From.Equals(min) || e.To.Equals(min)))
                {
                    if (edge.To.Equals(min))
                    {
                        if (heap.Contains(edge.From as VertexMST <T>) &&
                            edge.Weight < (edge.From as VertexMST <T>).Key)
                        {
                            edge.From.Predecessor            = min;
                            (edge.From as VertexMST <T>).Key = edge.Weight;
                        }
                    }
                    else
                    {
                        if (heap.Contains(edge.To as VertexMST <T>) &&
                            edge.Weight < (edge.To as VertexMST <T>).Key)
                        {
                            edge.To.Predecessor            = min;
                            (edge.To as VertexMST <T>).Key = edge.Weight;
                        }
                    }
                }
            }
        }
Exemplo n.º 2
0
 public int CompareTo(VertexMST <T> other)
 {
     return(Key.CompareTo(other.Key));
 }
Exemplo n.º 3
0
 private void MakeSet(VertexMST <T> vertex)
 {
     vertex.Rank   = 0;
     vertex.Parent = vertex;
 }