# Maximal independent set from a given Graph using Backtracking

• Difficulty Level : Hard
• Last Updated : 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

 `// C++ Program to print the``// independent sets and``// maximal independent sets``// of the given graph` `#include ``using` `namespace` `std;` `// To store all the independent``// sets of the graph``set > independentSets;` `// To store all maximal independent``// sets in the graph``set > maximalIndependentSets;` `map, ``int``> edges;``vector<``int``> vertices;` `// Function to print all independent sets``void` `printAllIndependentSets()``{``    ``for` `(``auto` `iter : independentSets) {``        ``cout << ``"{ "``;``        ``for` `(``auto` `iter2 : iter) {``            ``cout << iter2 << ``" "``;``        ``}``        ``cout << ``"}"``;``    ``}``    ``cout << endl;``}` `// Function to extract all``// maximal independent sets``void` `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 sets``void` `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 Program``int` `main()``{``    ``int` `V = 3, E = 0;` `    ``for` `(``int` `i = 1; i <= V; i++)``        ``vertices.push_back(i);` `    ``vector > inputEdges;` `    ``pair<``int``, ``int``> edge;``    ``int` `x, y;``    ``for` `(``int` `i = 0; i < E; i++) {``          ``cout< tempSolutionSet;` `    ``findAllIndependentSets(1,``                           ``V,``                           ``tempSolutionSet);` `    ``printAllIndependentSets();` `    ``printMaximalIndependentSets();` `    ``return` `0;``}`

## Python3

 `# Python3 Program to print the``# independent sets and``# maximal independent sets``# of the given graph` `# To store all the independent``# sets of the graph``independentSets``=``set``()` `# To store all maximal independent``# sets in the graph``maximalIndependentSets``=``set``()` `edges``=``dict``()``vertices``=``[]` `# Function to print all independent sets``def` `printAllIndependentSets():``    ``for` `itr ``in` `independentSets:``        ``print``(``"{"``,end``=``" "``)``        ``for` `itr2 ``in` `itr:``            ``print``(itr2,end``=` `" "``)``        ` `        ``print``(``"}"``,end``=``'')``    ` `    ``print``()`  `# Function to extract all``# maximal independent sets``def` `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 sets``def` `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 Program``if` `__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()`

Output:

```{ }{ 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)

My Personal Notes arrow_drop_up