Vertex Cover Problem
Pattern: BFS and DFS
A vertex cover is a set of vertices touching every edge. Finding the smallest one is NP-hard, so for the small graphs here, try every subset of vertices as a bitmask and keep the smallest that covers all edges.
The problem
Given an undirected graph with at most 16 vertices, return the size of a smallest vertex cover: a set of vertices such that every edge has at least one end in the set. The GFG page explains a fast approximate method; this guide asks for the exact minimum.
Think first
- How many subsets of vertices are there?
- How do you check one subset?
- Why is a greedy choice not enough?
Hints
Brute force, and why it fails
This is already the brute force; branch-and-bound or matching (for bipartite graphs) can do better.
The key insight
With n ≤ 16, enumerating 2ⁿ bitmasks is fast, and each check is O(E).
Dry run
5 vertices, edges 0-1, 0-2, 1-3, 3-4, 4-2 (a 5-cycle).
The plan
best = n
for mask in 0 .. 2^n - 1: if popcount(mask) < best and every edge has an end in mask: best = popcount
Complexity
- Time
O(2ⁿ × E)- Space
O(1)
Every subset, each checked against every edge.
Edge cases
- No edges: 0.
- One edge: 1.
- A star: 1 (the centre).
I've built my logic, show the code
Java
class Solution {
public int vertexCover(int n, int[][] edges) {
int best = n;
for (int mask = 0; mask < (1 << n); mask++) { // every set of vertices (n is small)
if (Integer.bitCount(mask) >= best) continue;
boolean covers = true;
for (int[] e : edges) if ((mask >> e[0] & 1) == 0 && (mask >> e[1] & 1) == 0) { covers = false; break; }
if (covers) best = Integer.bitCount(mask); // every edge touches the set
}
return best;
}
}C++
class Solution {
public:
int vertexCover(int n, vector<vector<int>>& edges) {
int best = n;
for (int mask = 0; mask < (1 << n); mask++) { // every set of vertices (n is small)
int size = __builtin_popcount(mask);
if (size >= best) continue;
bool covers = true;
for (const vector<int>& e : edges) if ((mask >> e[0] & 1) == 0 && (mask >> e[1] & 1) == 0) { covers = false; break; }
if (covers) best = size; // every edge touches the set
}
return best;
}
};Python
class Solution:
def vertexCover(self, n: int, edges: list[list[int]]) -> int:
best = n
for mask in range(1 << n): # every set of vertices (n is small)
size = bin(mask).count("1")
if size < best and all(mask >> u & 1 or mask >> v & 1 for u, v in edges):
best = size # every edge touches the set
return bestCommon mistakes
- Using the approximate algorithm and calling it the minimum.
- Shifting by more than 31 bits.