-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathKCentersGreedyApproximation.cs
More file actions
50 lines (39 loc) · 1.52 KB
/
KCentersGreedyApproximation.cs
File metadata and controls
50 lines (39 loc) · 1.52 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
using System;
using System.Linq;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.KCenters;
public class KCentersGreedyApproximation
{
#pragma warning disable CA1822 // Mark members as static
public int[] GetKCenters(int[][] graph, int centers)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return Array.Empty<int>();
var result = new int[centers];
var foundCentersCount = 0;
result[foundCentersCount] = 0;
foundCentersCount++;
while (foundCentersCount < result.Length)
{
var maxDistanceFromCentersVertexIndex = -1;
var maxDistanceFromCentersVertex = int.MinValue;
for (var i = 0; i < graph.Length; i++)
{
if (result.Contains(i)) continue;
var minDistance = int.MaxValue;
for (var c = 0; c < foundCentersCount; c++)
{
if (c == i) continue;
if (graph[c][i] < minDistance) minDistance = graph[c][i];
}
if (maxDistanceFromCentersVertexIndex == -1 || maxDistanceFromCentersVertex < minDistance)
{
maxDistanceFromCentersVertexIndex = i;
maxDistanceFromCentersVertex = minDistance;
}
}
result[foundCentersCount] = maxDistanceFromCentersVertexIndex;
foundCentersCount++;
}
return result;
}
}