-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKruskalMinimumSpanningTree.cs
More file actions
51 lines (40 loc) · 1.71 KB
/
KruskalMinimumSpanningTree.cs
File metadata and controls
51 lines (40 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.Collections.Generic;
using System.Linq;
using AlgorithmsAndDataStructures.Algorithms.Graph.Common;
using AlgorithmsAndDataStructures.Algorithms.Graph.Misc;
using AlgorithmsAndDataStructures.DataStructures.Graph;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.MinimumSpanningTree;
public class KruskalMinimumSpanningTree
{
#pragma warning disable CA1822 // Mark members as static
public int GetMinimumSpanningTreeWeight(WeightedGraphVertex[] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return default;
var minimumSpanningTreeWeight = 0;
// ReSharper disable once CollectionNeverQueried.Local
var minimumSpanningTree = new List<WeightedGraphNodeEdge>();
var spanningTree = new GraphVertex<int>[graph.Length];
for (var i = 0; i < spanningTree.Length; i++) spanningTree[i] = new GraphVertex<int>();
var spanningTreeSize = 0;
var currentEdgeIndex = 0;
var edges = graph.SelectMany(arg => arg.Edges).OrderBy(arg => arg.Weight).ToArray();
while (spanningTreeSize < graph.Length - 1)
{
var currentEdge = edges[currentEdgeIndex];
spanningTree[currentEdge.From].AdjacentVertices.Add(currentEdge.To);
if (!CycleDetector.IsCyclic(spanningTree))
{
spanningTreeSize++;
minimumSpanningTreeWeight += currentEdge.Weight;
minimumSpanningTree.Add(currentEdge);
}
else
{
spanningTree[currentEdge.From].AdjacentVertices.Remove(currentEdge.To);
}
currentEdgeIndex++;
}
return minimumSpanningTreeWeight;
}
}