示例#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;
                        }
                    }
                }
            }
        }
示例#2
0
        //edges' weights cannot be negative
        public void Dijkstra(IVertex <T> source)
        {
            Initialize(source);
            //var set = new List<VertexSSSP<T>>();
            var heap = new MinHeap <VertexSSSP <T> >(vertices.Count + edges.Count);

            heap.Insert(source as VertexSSSP <T>);
            while (!heap.IsEmpty)
            {
                var vertex = heap.Extract();
                if (vertex.Visited)
                {
                    continue;
                }
                vertex.Visited = true;
                //set.Add(node.Key);
                foreach (var edge in edges.Where((e) => e.From.Equals(vertex)))
                {
                    Relax(edge.From, edge.To, edge.Weight);
                    heap.Insert(edge.To as VertexSSSP <T>);
                }
            }
        }