Example #1
0
        private BinaryTreeNode MergeNodesByWeightIntoOne(MinHeapUniversal <BinaryTreeNode> minHeap)
        {
            while (minHeap.GetHeapSize() != 1)
            {
                var firstSmallestNode  = minHeap.ExtractMinElement();
                var secondSmallestNode = minHeap.ExtractMinElement();

                var superNode = new BinaryTreeNode();
                superNode.SetKey(firstSmallestNode.GetKey() + secondSmallestNode.GetKey());
                superNode.LeftChild  = firstSmallestNode;
                superNode.RightChild = secondSmallestNode;
                minHeap.InsertElement(superNode);
            }

            return(minHeap.ExtractMinElement());
        }
        public int[] GetShortestPaths(Dictionary <int, NodeWeighted> graph, int startingVertex)
        {
            var visitedNodesCount     = 1;
            var closestUnvisitedNodes = new MinHeapUniversal <NodeWeighted>();

            var pathLengths = new int[graph.Count + 1];
            var firstNode   = graph[startingVertex];

            firstNode.Value             = 0;
            pathLengths[startingVertex] = 0;
            var lastAddedNode = firstNode;

            lastAddedNode.Visit();
            while (visitedNodesCount++ != graph.Count - 1)
            {
                var unvisitedHeadNodes = lastAddedNode.Neighbours.FindAll(x => !x.Item1.IsVisited);

                foreach (var nodeWeightTuple in unvisitedHeadNodes)
                {
                    var(neighbour, edgeLength) = nodeWeightTuple;
                    var pathLength   = edgeLength + lastAddedNode.Value;
                    var isNodeInHeap = neighbour.HeapIndex != 0;

                    if (isNodeInHeap)
                    {
                        closestUnvisitedNodes.TryDecreaseKey(neighbour.HeapIndex, pathLength);
                    }
                    else
                    {
                        neighbour.Value = pathLength;
                        closestUnvisitedNodes.InsertElement(neighbour);
                    }
                }

                if (closestUnvisitedNodes.GetHeapSize() != 0)
                {
                    lastAddedNode = closestUnvisitedNodes.ExtractMinElement();
                    lastAddedNode.Visit();
                    lastAddedNode.HeapIndex       = 0;
                    pathLengths[lastAddedNode.Id] = lastAddedNode.Value;
                }
            }

            return(pathLengths);
        }