Maximal independent set from a given Graph using Backtracking - GeeksforGeeks

25 Nov, 2021
Given an undirected graph with V vertices and E edges, the task is to print all the independent sets and also find the maximal independent set(s).  
Independent set is a set of vertices such that any two vertices in the set do not have a direct edge between them.
 
Maximal independent set is an independent set having highest number of vertices.  
Note: There can be more than one independent and maximal independent sets for a given graph.Examples: 
Input: V = 3, E = 0 Graph:  
Graph for example 1
Output: { }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 } { 1 2 3 } Explanation: The first line represents all the possible independent sets for the given graph. The second line has the maximal independent sets possible for the given graph.Input: V = 4, E = 4 Graph:  
Graph for example 2
Output: { }{ 1 }{ 1 3 }{ 2 }{ 2 4 }{ 3 }{ 4 } { 1 3 }{ 2 4 }  
 
Approach: The idea is to use Backtracking to solve the problem. At every step, we need to check whether the current node has any direct edge with any of the nodes already present in our independent set. If not, we can add it to our independent set and recursively repeat the same process for all the nodes. 
Illustration: Recursion tree for the first example:  
Backtracking tree for all possible sets
In the above backtracking tree we will choose only those sets which are produced after adding a safe node to maintain the set as an independent set.
Below is the implementation of the above approach: 
CPP
Python3
// C++ Program to print the// independent sets and// maximal independent sets// of the given graph #include <bits/stdc++.h>using namespace std; // To store all the independent// sets of the graphset<set<int> > independentSets; // To store all maximal independent// sets in the graphset<set<int> > maximalIndependentSets; map<pair<int, int>, int> edges;vector<int> vertices; // Function to print all independent setsvoid printAllIndependentSets(){    for (auto iter : independentSets) {        cout << "{ ";        for (auto iter2 : iter) {            cout << iter2 << " ";        }        cout << "}";    }    cout << endl;} // Function to extract all// maximal independent setsvoid printMaximalIndependentSets(){    int maxCount = 0;    int localCount = 0;    for (auto iter : independentSets) {         localCount = 0;        for (auto iter2 : iter) {            localCount++;        }        if (localCount > maxCount)            maxCount = localCount;    }    for (auto iter : independentSets) {         localCount = 0;        set<int> tempMaximalSet;         for (auto iter2 : iter) {            localCount++;            tempMaximalSet.insert(iter2);        }        if (localCount == maxCount)            maximalIndependentSets                .insert(tempMaximalSet);    }    for (auto iter : maximalIndependentSets) {        cout << "{ ";        for (auto iter2 : iter) {            cout << iter2 << " ";        }        cout << "}";    }    cout << endl;} // Function to check if a// node is safe node.bool isSafeForIndependentSet(    int vertex,    set<int> tempSolutionSet){    for (auto iter : tempSolutionSet) {        if (edges[make_pair(iter, vertex)]) {            return false;        }    }    return true;} // Recursive function to find// all independent setsvoid findAllIndependentSets(    int currV,    int setSize,    set<int> tempSolutionSet){    for (int i = currV; i <= setSize; i++) {        if (isSafeForIndependentSet(                vertices[i - 1],                tempSolutionSet)) {            tempSolutionSet                .insert(vertices[i - 1]);            findAllIndependentSets(                i + 1,                setSize,                tempSolutionSet);            tempSolutionSet                .erase(vertices[i - 1]);        }    }    independentSets        .insert(tempSolutionSet);} // Driver Programint main(){    int V = 3, E = 0;     for (int i = 1; i <= V; i++)        vertices.push_back(i);     vector<pair<int, int> > inputEdges;     pair<int, int> edge;    int x, y;    for (int i = 0; i < E; i++) {          cout<<i<<endl;        edge.first = inputEdges[i].first;        edge.second = inputEdges[i].second;        edges[edge] = 1;        int t = edge.first;        edge.first = edge.second;        edge.second = t;        edges[edge] = 1;    }     set<int> tempSolutionSet;     findAllIndependentSets(1,                           V,                           tempSolutionSet);     printAllIndependentSets();     printMaximalIndependentSets();     return 0;}
# Python3 Program to print the# independent sets and# maximal independent sets# of the given graph # To store all the independent# sets of the graphindependentSets=set() # To store all maximal independent# sets in the graphmaximalIndependentSets=set() edges=dict()vertices=[] # Function to print all independent setsdef printAllIndependentSets():    for itr in independentSets:        print("{",end=" ")        for itr2 in itr:            print(itr2,end= " ")                 print("}",end='')         print()  # Function to extract all# maximal independent setsdef printMaximalIndependentSets():    maxCount = 0;localCount = 0    for itr in independentSets:        localCount = 0        for itr2 in itr:            localCount+=1                 if (localCount > maxCount):            maxCount = localCount         for itr in independentSets:         localCount = 0        tempMaximalSet=set()         for itr2 in itr:            localCount+=1            tempMaximalSet.add(itr2)                 if (localCount == maxCount):            maximalIndependentSets.add(frozenset(tempMaximalSet))         for itr in maximalIndependentSets :        print("{",end=" ")        for itr2 in itr:            print(itr2,end=" ")                 print("}",end="")         print()  # Function to check if a# node is safe node.def isSafeForIndependentSet(vertex, tempSolutionSet):    for itr in tempSolutionSet:        if (itr, vertex) in edges:            return False     return True  # Recursive function to find# all independent setsdef findAllIndependentSets(currV, setSize, tempSolutionSet):    for i in range(currV,setSize+1):        if (isSafeForIndependentSet(vertices[i - 1], tempSolutionSet)) :            tempSolutionSet.add(vertices[i - 1])            findAllIndependentSets(i + 1, setSize, tempSolutionSet)            tempSolutionSet.remove(vertices[i - 1])             independentSets.add(frozenset(tempSolutionSet))  # Driver Programif __name__ == '__main__':    V = 3; E = 0     for i in range(1,V+1):        vertices.append(i)     inputEdges=[]     for i in range(E):        edges[inputEdges[i]]=True        edges[(inputEdges[i][1],inputEdges[i][0])]=True          tempSolutionSet=set()     findAllIndependentSets(1, V, tempSolutionSet)     printAllIndependentSets()     printMaximalIndependentSets()
{ }{ 1 }{ 1 2 }{ 1 2 3 }{ 1 3 }{ 2 }{ 2 3 }{ 3 }
{ 1 2 3 }
 
Time Complexity: O(2 ^ N)
Auxiliary Space: O(2 ^ N)
sooda367
pankajsharmagfg
ruhelaa48
amartyaghoshgfg
Algorithms
Backtracking
Competitive Programming
Data Structures
Graph
Data Structures
Graph
Backtracking
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
N Queen Problem | Backtracking-3
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Backtracking | Introduction
Rat in a Maze | Backtracking-2