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:Â Â
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: Â
// Java Program to print the// independent sets and// maximal independent sets// of the given graphimportjava.util.*;publicclassIndependentSets{// To store all the independent sets of the graphstaticSet<Set<Integer>>independentSets=newHashSet<>();// To store all maximal independent sets in the graphstaticSet<Set<Integer>>maximalIndependentSets=newHashSet<>();staticMap<int[],Boolean>edges=newHashMap<>();staticList<Integer>vertices=newArrayList<>();// Function to print all independent setsstaticvoidprintAllIndependentSets(){for(Set<Integer>set:independentSets){System.out.print("{ ");for(intvertex:set){System.out.print(vertex+" ");}System.out.print("}");}System.out.println();}// Function to extract all maximal independent setsstaticvoidprintMaximalIndependentSets(){intmaxCount=0;intlocalCount;for(Set<Integer>set:independentSets){localCount=0;for(intvertex:set){localCount++;}if(localCount>maxCount){maxCount=localCount;}}for(Set<Integer>set:independentSets){localCount=0;Set<Integer>tempMaximalSet=newHashSet<>();for(intvertex:set){localCount++;tempMaximalSet.add(vertex);}if(localCount==maxCount){maximalIndependentSets.add(Collections.unmodifiableSet(tempMaximalSet));}}for(Set<Integer>set:maximalIndependentSets){System.out.print("{ ");for(intvertex:set){System.out.print(vertex+" ");}System.out.print("}");}System.out.println();}// Function to check if a node is safe node.staticbooleanisSafeForIndependentSet(intvertex,Set<Integer>tempSolutionSet){for(intnode:tempSolutionSet){if(edges.get(newint[]{node,vertex})!=null){returnfalse;}}returntrue;}// Recursive function to find all independent setsstaticvoidfindAllIndependentSets(intcurrV,intsetSize,Set<Integer>tempSolutionSet){for(inti=currV;i<=setSize;i++){if(isSafeForIndependentSet(vertices.get(i-1),tempSolutionSet)){tempSolutionSet.add(vertices.get(i-1));findAllIndependentSets(i+1,setSize,tempSolutionSet);tempSolutionSet.remove(vertices.get(i-1));}}independentSets.add(Collections.unmodifiableSet(newHashSet<>(tempSolutionSet)));}// Driver Programpublicstaticvoidmain(String[]args){intV=3,E=2;for(inti=1;i<=V;i++){vertices.add(i);}List<int[]>inputEdges=newArrayList<>();inputEdges.add(newint[]{1,2});inputEdges.add(newint[]{2,3});for(inti=0;i<E;i++){if(i<inputEdges.size()){edges.put(inputEdges.get(i),true);edges.put(newint[]{inputEdges.get(i)[1],inputEdges.get(i)[0]},true);}}Set<Integer>tempSolutionSet=newHashSet<>();findAllIndependentSets(1,V,tempSolutionSet);printAllIndependentSets();printMaximalIndependentSets();}}
Python
# 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 setsdefprintAllIndependentSets():foritrinindependentSets:print("{",end=" ")foritr2initr:print(itr2,end=" ")print("}",end='')print()# Function to extract all# maximal independent setsdefprintMaximalIndependentSets():maxCount=0;localCount=0foritrinindependentSets:localCount=0foritr2initr:localCount+=1if(localCount>maxCount):maxCount=localCountforitrinindependentSets:localCount=0tempMaximalSet=set()foritr2initr:localCount+=1tempMaximalSet.add(itr2)if(localCount==maxCount):maximalIndependentSets.add(frozenset(tempMaximalSet))foritrinmaximalIndependentSets:print("{",end=" ")foritr2initr:print(itr2,end=" ")print("}",end="")print()# Function to check if a# node is safe node.defisSafeForIndependentSet(vertex,tempSolutionSet):foritrintempSolutionSet:if(itr,vertex)inedges:returnFalsereturnTrue# Recursive function to find# all independent setsdeffindAllIndependentSets(currV,setSize,tempSolutionSet):foriinrange(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=0foriinrange(1,V+1):vertices.append(i)inputEdges=[]foriinrange(E):edges[inputEdges[i]]=Trueedges[(inputEdges[i][1],inputEdges[i][0])]=TruetempSolutionSet=set()findAllIndependentSets(1,V,tempSolutionSet)printAllIndependentSets()printMaximalIndependentSets()
C#
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;classProgram{// Define the independent sets and maximal independent sets as SortedSet of SortedSetstaticSortedSet<SortedSet<int>>independentSets=newSortedSet<SortedSet<int>>(newComparerForSets());staticSortedSet<SortedSet<int>>maximalIndependentSets=newSortedSet<SortedSet<int>>(newComparerForSets());// Define the edges as a Dictionary with Tuple as key and int as valuestaticDictionary<Tuple<int,int>,int>edges=newDictionary<Tuple<int,int>,int>();// Define the vertices as a List of intstaticList<int>vertices=newList<int>();staticvoidMain(){// Define the number of vertices and edgesintV=3,E=0;// Add the vertices to the vertices listfor(inti=1;i<=V;i++)vertices.Add(i);// Define the input edges as a List of TupleList<Tuple<int,int>>inputEdges=newList<Tuple<int,int>>();Tuple<int,int>edge;// Add the edges to the edges dictionaryfor(inti=0;i<E;i++){Console.WriteLine(i);edge=Tuple.Create(inputEdges[i].Item1,inputEdges[i].Item2);edges[edge]=1;intt=edge.Item1;edge=Tuple.Create(edge.Item2,t);edges[edge]=1;}// Define the temporary solution set as a SortedSetSortedSet<int>tempSolutionSet=newSortedSet<int>();// Find all independent setsfindAllIndependentSets(1,V,tempSolutionSet);// Print all independent sets and maximal independent setsprintAllIndependentSets();printMaximalIndependentSets();}// Method to print all independent setsstaticvoidprintAllIndependentSets(){foreach(variterinindependentSets){Console.Write("{ ");foreach(variter2initer){Console.Write(iter2+" ");}Console.Write("}");}Console.WriteLine();}// Method to print maximal independent setsstaticvoidprintMaximalIndependentSets(){intmaxCount=0;intlocalCount=0;foreach(variterinindependentSets){localCount=0;foreach(variter2initer){localCount++;}if(localCount>maxCount)maxCount=localCount;}foreach(variterinindependentSets){localCount=0;SortedSet<int>tempMaximalSet=newSortedSet<int>();foreach(variter2initer){localCount++;tempMaximalSet.Add(iter2);}if(localCount==maxCount)maximalIndependentSets.Add(tempMaximalSet);}foreach(variterinmaximalIndependentSets){Console.Write("{ ");foreach(variter2initer){Console.Write(iter2+" ");}Console.Write("}");}Console.WriteLine();}// Method to check if a vertex is safe for independent setstaticboolisSafeForIndependentSet(intvertex,SortedSet<int>tempSolutionSet){foreach(variterintempSolutionSet){if(edges.ContainsKey(Tuple.Create(iter,vertex))){returnfalse;}}returntrue;}// Method to find all independent setsstaticvoidfindAllIndependentSets(intcurrV,intsetSize,SortedSet<int>tempSolutionSet){for(inti=currV;i<=setSize;i++){if(isSafeForIndependentSet(vertices[i-1],tempSolutionSet)){tempSolutionSet.Add(vertices[i-1]);findAllIndependentSets(i+1,setSize,newSortedSet<int>(tempSolutionSet));tempSolutionSet.Remove(vertices[i-1]);}}independentSets.Add(newSortedSet<int>(tempSolutionSet));}}// Class to compare sets for sortingpublicclassComparerForSets:IComparer<SortedSet<int>>{publicintCompare(SortedSet<int>x,SortedSet<int>y){if(x.Count!=y.Count)returnx.Count.CompareTo(y.Count);returnString.Join(",",x).CompareTo(String.Join(",",y));}}
JavaScript
// JavaScript Program to print the// independent sets and// maximal independent sets// of the given graph// To store all the independent// sets of the graphletindependentSets=newSet();// To store all maximal independent// sets in the graphletmaximalIndependentSets=newSet();letedges={};letvertices=[];// Function to print all independent setsfunctionprintAllIndependentSets(){for(letitrofindependentSets){process.stdout.write("{ ");for(letitr2ofitr){process.stdout.write(itr2+" ");}process.stdout.write("}");}console.log();}// Function to extract all// maximal independent setsfunctionprintMaximalIndependentSets(){letmaxCount=0;letlocalCount=0;for(letitrofindependentSets){localCount=0;for(letitr2ofitr){localCount+=1;}if(localCount>maxCount){maxCount=localCount;}}for(letitrofindependentSets){localCount=0;lettempMaximalSet=newSet();for(letitr2ofitr){localCount+=1;tempMaximalSet.add(itr2);}if(localCount==maxCount){maximalIndependentSets.add(newSet(tempMaximalSet));}}for(letitrofmaximalIndependentSets){process.stdout.write("{ ");for(letitr2ofitr){process.stdout.write(itr2+" ");}process.stdout.write("}");}console.log();}// Function to check if a// node is safe node.functionisSafeForIndependentSet(vertex,tempSolutionSet){for(letitroftempSolutionSet){if(edges[[itr,vertex]]){returnfalse;}}returntrue;}// Recursive function to find// all independent setsfunctionfindAllIndependentSets(currV,setSize,tempSolutionSet){for(leti=currV;i<=setSize;i++){if(isSafeForIndependentSet(vertices[i-1],tempSolutionSet)){tempSolutionSet.add(vertices[i-1]);findAllIndependentSets(i+1,setSize,tempSolutionSet);tempSolutionSet.delete(vertices[i-1]);}}independentSets.add(newSet(tempSolutionSet));}// Driver ProgramletV=3;letE=0;for(leti=1;i<=V;i++){vertices.push(i);}letinputEdges=[];for(leti=0;i<E;i++){edges[[inputEdges[i][0],inputEdges[i][1]]]=true;edges[[inputEdges[i][1],inputEdges[i][0]]]=true;}lettempSolutionSet=newSet();findAllIndependentSets(1,V,tempSolutionSet);printAllIndependentSets();printMaximalIndependentSets();// Expected output:// { 1 }// { 2 }// { 3 }// { 1 3 }// { 1 2 }// { 2 3 }// { 1 2 3 }