public static Graph <T> CreateMinimumSpanningTreeFor <T>(Graph <T> graph) where T : class, IEquatable <T> { var visitedVertices = new HashSet <Vertex <T> >(); if (!graph.IsConnected || graph.IsDirected) { throw new InvalidOperationException("The graph doesn't meet the characteristics to be used with Prim algorythm."); } var minBinaryHeap = new MinBinaryHeap <T>(graph, graph.Vertices.Values.First()); while (!minBinaryHeap.IsEmpty()) { var vertexOnAnalysis = minBinaryHeap.ExtractFromTop(); foreach (var edge in vertexOnAnalysis.AdjacentEdges.Where(x => !visitedVertices.Contains(x.To) && !visitedVertices.Contains(x.From))) { var other = edge.To == vertexOnAnalysis ? edge.From : edge.To; if (minBinaryHeap.Contains(other, out float?value)) { if (value.Value > edge.Weight.Value) { minBinaryHeap.ReplaceValue(other, edge.Weight.Value, edge); } } } visitedVertices.Add(vertexOnAnalysis); } return(BuildNewGraph(graph, minBinaryHeap)); }
private void CheckNeighbour(PathNode currentNode, PathNode neighbour, PathNode endNode) { int newDistanceCost = currentNode.GCost + currentNode.GetDistanceCost(neighbour); if (newDistanceCost < neighbour.GCost || !_openSet.Contains(neighbour)) { neighbour.UpdateNode(newDistanceCost, neighbour.GetDistanceCost(endNode), currentNode); if (!_openSet.Contains(neighbour)) { _openSet.Add(neighbour); } else { _openSet.Heapify(neighbour); } } }