|
| 1 | +""" |
| 2 | +* Author: Manuel Di Lullo (https://github.com/manueldilullo) |
| 3 | +* Description: Approximization algorithm for minimum vertex cover problem. |
| 4 | + Greedy Approach. Uses graphs represented with an adjacency list |
| 5 | +
|
| 6 | +URL: https://mathworld.wolfram.com/MinimumVertexCover.html |
| 7 | +URL: https://cs.stackexchange.com/questions/129017/greedy-algorithm-for-vertex-cover |
| 8 | +""" |
| 9 | + |
| 10 | +import heapq |
| 11 | + |
| 12 | + |
| 13 | +def greedy_min_vertex_cover(graph: dict) -> set: |
| 14 | + """ |
| 15 | + Greedy APX Algorithm for min Vertex Cover |
| 16 | + @input: graph (graph stored in an adjacency list where each vertex |
| 17 | + is represented with an integer) |
| 18 | + @example: |
| 19 | + >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} |
| 20 | + >>> greedy_min_vertex_cover(graph) |
| 21 | + {0, 1, 2, 4} |
| 22 | + """ |
| 23 | + # queue used to store nodes and their rank |
| 24 | + queue = [] |
| 25 | + |
| 26 | + # for each node and his adjacency list add them and the rank of the node to queue |
| 27 | + # using heapq module the queue will be filled like a Priority Queue |
| 28 | + # heapq works with a min priority queue, so I used -1*len(v) to build it |
| 29 | + for key, value in graph.items(): |
| 30 | + # O(log(n)) |
| 31 | + heapq.heappush(queue, [-1 * len(value), (key, value)]) |
| 32 | + |
| 33 | + # chosen_vertices = set of chosen vertices |
| 34 | + chosen_vertices = set() |
| 35 | + |
| 36 | + # while queue isn't empty and there are still edges |
| 37 | + # (queue[0][0] is the rank of the node with max rank) |
| 38 | + while queue and queue[0][0] != 0: |
| 39 | + # extract vertex with max rank from queue and add it to chosen_vertices |
| 40 | + argmax = heapq.heappop(queue)[1][0] |
| 41 | + chosen_vertices.add(argmax) |
| 42 | + |
| 43 | + # Remove all arcs adjacent to argmax |
| 44 | + for elem in queue: |
| 45 | + # if v haven't adjacent node, skip |
| 46 | + if elem[0] == 0: |
| 47 | + continue |
| 48 | + # if argmax is reachable from elem |
| 49 | + # remove argmax from elem's adjacent list and update his rank |
| 50 | + if argmax in elem[1][1]: |
| 51 | + index = elem[1][1].index(argmax) |
| 52 | + del elem[1][1][index] |
| 53 | + elem[0] += 1 |
| 54 | + # re-order the queue |
| 55 | + heapq.heapify(queue) |
| 56 | + return chosen_vertices |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + import doctest |
| 61 | + |
| 62 | + doctest.testmod() |
| 63 | + |
| 64 | + # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} |
| 65 | + # print(f"Minimum vertex cover:\n{greedy_min_vertex_cover(graph)}") |
0 commit comments