-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgreedy_vc.py
More file actions
42 lines (37 loc) · 1.23 KB
/
greedy_vc.py
File metadata and controls
42 lines (37 loc) · 1.23 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
import integral_vc
class GreedyVC:
"""
Class to implement Greedy Algorithm for Vertex Cover
"""
def printVertexCover(self, graph):
"""
Method to identify the vertex cover and cost generated by the Greedy Algorithm
Parameter:
Graph
Return:
Ratio of total cost of vertex cover to the optimal cost generated by the Integer Program
Logic:
Have a boolean value 'visited' for each vertices in the graph
Sort all the nodes based on their cost
Iterate through the sorted nodes
If the current node and its neighbour nodes are not visited
Set both nodes visited as True
Vertex Cover is the vertices that are visited
"""
visited = [False] * len(graph.nodes)
vc_cost = 0
# Consider all edges one by one
for u in sorted(graph.nodes(), key=lambda n: graph.nodes[n]['cost']):
if not visited[u]:
for v in graph.neighbors(u):
if not visited[v]:
visited[v] = True
visited[u] = True
break
# Print the vertex cover
for j in range(len(graph.nodes)):
if visited[j]:
vc_cost += graph.nodes[j]["cost"]
integral = integral_vc.IntegralVC()
opt_cost = integral.vc_integral(graph)
return round(vc_cost/opt_cost, 3)