Skip to content

Commit 7749eb3

Browse files
authored
Add Minimum Spanning Tree in C# (#4878)
1 parent 5845d93 commit 7749eb3

File tree

1 file changed

+108
-0
lines changed

1 file changed

+108
-0
lines changed
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
5+
public static class Program
6+
{
7+
private static void ShowUsage()
8+
{
9+
Console.Error.WriteLine("Usage: please provide a comma-separated list of integers");
10+
Environment.Exit(1);
11+
}
12+
13+
private static List<int> ParseIntegerList(string input)
14+
{
15+
if (string.IsNullOrWhiteSpace(input))
16+
ShowUsage();
17+
18+
var tokens = input
19+
.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
20+
21+
if (tokens.Length < 4) // Minimum size for a 2x2 matrix
22+
ShowUsage();
23+
24+
var numbers = new List<int>();
25+
foreach (var token in tokens)
26+
{
27+
if (!int.TryParse(token, out int value))
28+
ShowUsage();
29+
30+
numbers.Add(value);
31+
}
32+
33+
int dim = (int)Math.Sqrt(numbers.Count);
34+
if (dim * dim != numbers.Count)
35+
ShowUsage();
36+
37+
return numbers;
38+
}
39+
40+
private static int MinimumSpanningTreeWeight(List<int> adjacencyMatrix, int dimension)
41+
{
42+
var includedInMST = new bool[dimension];
43+
var minEdgeWeight = new int[dimension];
44+
45+
for (int i = 0; i < dimension; i++)
46+
{
47+
minEdgeWeight[i] = int.MaxValue;
48+
includedInMST[i] = false;
49+
}
50+
51+
minEdgeWeight[0] = 0;
52+
int totalWeight = 0;
53+
54+
for (int count = 0; count < dimension; count++)
55+
{
56+
int currentMinWeight = int.MaxValue;
57+
int currentNode = -1;
58+
59+
for (int i = 0; i < dimension; i++)
60+
{
61+
if (!includedInMST[i] && minEdgeWeight[i] < currentMinWeight)
62+
{
63+
currentMinWeight = minEdgeWeight[i];
64+
currentNode = i;
65+
}
66+
}
67+
68+
if (currentNode == -1)
69+
{
70+
ShowUsage();
71+
}
72+
73+
includedInMST[currentNode] = true;
74+
totalWeight += currentMinWeight;
75+
76+
for (int adjacent = 0; adjacent < dimension; adjacent++)
77+
{
78+
int edgeWeight = adjacencyMatrix[currentNode * dimension + adjacent];
79+
if (!includedInMST[adjacent] && edgeWeight != 0 && edgeWeight < minEdgeWeight[adjacent])
80+
{
81+
minEdgeWeight[adjacent] = edgeWeight;
82+
}
83+
}
84+
}
85+
86+
return totalWeight;
87+
}
88+
89+
public static int Main(string[] args)
90+
{
91+
if (args.Length != 1)
92+
ShowUsage();
93+
94+
var inputList = ParseIntegerList(args[0]);
95+
96+
var numbers = ParseIntegerList(args[0]);
97+
int dimension = (int)Math.Sqrt(numbers.Count);
98+
99+
int mstWeight = MinimumSpanningTreeWeight(numbers, dimension);
100+
101+
if (mstWeight == -1)
102+
ShowUsage();
103+
104+
Console.WriteLine(mstWeight);
105+
106+
return 0;
107+
}
108+
}

0 commit comments

Comments
 (0)