-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathVertexCoverSimpleApproximation.cs
More file actions
81 lines (62 loc) · 2.19 KB
/
VertexCoverSimpleApproximation.cs
File metadata and controls
81 lines (62 loc) · 2.19 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System.Collections.Generic;
using System.Linq;
namespace AlgorithmsAndDataStructures.Algorithms.Graph.VertexCover;
public class VertexCoverSimpleApproximation
{
#pragma warning disable CA1822 // Mark members as static
public List<int> GetVertexCover(int[][] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return new List<int>(0);
var visited = new bool[graph.Length];
for (var i = 0; i < graph.Length; i++)
{
if (visited[i]) continue;
for (var j = 0; j < graph.Length; j++)
{
if (graph[i][j] == 0) continue;
if (!visited[j] && i != j)
{
visited[j] = true;
visited[i] = true;
break;
}
}
}
var result = new List<int>();
for (var i = 0; i < visited.Length; i++)
if (visited[i])
result.Add(i);
return result;
}
#pragma warning disable CA1822 // Mark members as static
public List<int> GetVertexCoverOptimized(int[][] graph)
#pragma warning restore CA1822 // Mark members as static
{
if (graph is null) return new List<int>(0);
var visited = new int[graph.Length];
for (var i = 0; i < graph.Length; i++)
{
var vertexWithMaxDegree = -1;
for (var v = 0; v < graph.Length; v++)
if (visited[v] == 0 && (vertexWithMaxDegree == -1 || graph[vertexWithMaxDegree].Sum() < graph[v].Sum()))
vertexWithMaxDegree = v;
if (vertexWithMaxDegree < 0) break;
for (var j = 0; j < graph.Length; j++)
{
if (graph[vertexWithMaxDegree][j] == 0) continue;
if (visited[j] == 0 && vertexWithMaxDegree != j)
{
visited[j] = 1;
visited[vertexWithMaxDegree] = 2;
break;
}
}
}
var result = new List<int>();
for (var i = 0; i < visited.Length; i++)
if (visited[i] == 2)
result.Add(i);
return result;
}
}