For a Given a undirected graph , find a set of vertices such that no two vertices in this set are connected by an edge.
Can anyone help me understand why the below-mentioned algorithm is wrong?
- Iterate on vertices in increasing order of their degree.
- Choose a vertex into the set if it is not marked yet.
- Iterate on its neighbours and mark them unfit to be chosen.
Code
vector<pi> q;
for(int i=0; i<n; i++) {
q.pb({adj[i].size(), i});
}
sort(all(q));
vector<bool> chosen(n, false);
vector<int> ans;
for(auto x:q){
if(chosen[x.second])
continue;
ans.pb(x.second);
for(auto y:adj[x.second])
chosen[y] = true;
}