Problem
Given an undirected graph, find the minimum set of vertices such that every edge in the graph is incident to at least one vertex in the set (vertex cover). The goal is to minimize the size of this set.
Examples
Example 1
graph LR; A(0) --- B(1):::green B --- C(2) C --- D(3):::green & E(4):::green D --- E D --- F(5) E --- F D --- G(6) classDef green fill:#3CB371,stroke:#000,stroke-width:1px,color:#fff;
|
|
Solution
Method 1 – Greedy 2-Approximation Algorithm
Intuition
Since the problem is NP-hard, we use a greedy algorithm that repeatedly picks an edge and adds both its endpoints to the cover, removing all edges incident to those vertices. This gives a cover at most twice the size of the minimum.
Approach
- Initialize the cover set as empty.
- While there are uncovered edges:
- Pick any uncovered edge (u, v).
- Add both u and v to the cover set.
- Remove all edges incident to u or v.
- Return the cover set.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(N + M)
, where N is the number of vertices and M is the number of edges, since each edge and vertex is processed at most once. - 🧺 Space complexity:
O(N + M)
, for adjacency lists and bookkeeping.