APX Algorithm for min Vertex Cover using Matching Approach @input: graph (graph stored in an adjacency list where each vertex is represented as an integer) @example: >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} >>> matching_min_vertex_cov
(graph: dict)
| 9 | |
| 10 | |
| 11 | def matching_min_vertex_cover(graph: dict) -> set: |
| 12 | """ |
| 13 | APX Algorithm for min Vertex Cover using Matching Approach |
| 14 | @input: graph (graph stored in an adjacency list where each vertex |
| 15 | is represented as an integer) |
| 16 | @example: |
| 17 | >>> graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} |
| 18 | >>> matching_min_vertex_cover(graph) |
| 19 | {0, 1, 2, 4} |
| 20 | """ |
| 21 | # chosen_vertices = set of chosen vertices |
| 22 | chosen_vertices = set() |
| 23 | # edges = list of graph's edges |
| 24 | edges = get_edges(graph) |
| 25 | |
| 26 | # While there are still elements in edges list, take an arbitrary edge |
| 27 | # (from_node, to_node) and add his extremity to chosen_vertices and then |
| 28 | # remove all arcs adjacent to the from_node and to_node |
| 29 | while edges: |
| 30 | from_node, to_node = edges.pop() |
| 31 | chosen_vertices.add(from_node) |
| 32 | chosen_vertices.add(to_node) |
| 33 | for edge in edges.copy(): |
| 34 | if from_node in edge or to_node in edge: |
| 35 | edges.discard(edge) |
| 36 | return chosen_vertices |
| 37 | |
| 38 | |
| 39 | def get_edges(graph: dict) -> set: |