Open In App

Maximal independent set from a given Graph using Backtracking

Improve
Improve
Like Article
Like
Save
Share
Report

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 https://write.geeksforgeeks.org/improve-post/5126048independent 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




#include <bits/stdc++.h>
using namespace std;
set<set<int> > independentSets;
set<set<int> > maximalIndependentSets;
map<pair<int, int>, int> edges;
vector<int> vertices;
void printAllIndependentSets(){
    for (auto iter : independentSets) {
        cout << "{ ";
        for (auto iter2 : iter) {
            cout << iter2 << " ";   }
        cout << "}";    }
    cout << endl;}
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;}
bool isSafeForIndependentSet(
    int vertex,
    set<int> tempSolutionSet){
    for (auto iter : tempSolutionSet) {
        if (edges[make_pair(iter, vertex)]) {
            return false; } }
    return true;}
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);}
int 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;}


Java




// Java Program to print the
// independent sets and
// maximal independent sets
// of the given graph
import java.util.*;
 
public class IndependentSets {
    // To store all the independent sets of the graph
    static Set<Set<Integer> > independentSets
        = new HashSet<>();
 
    // To store all maximal independent sets in the graph
    static Set<Set<Integer> > maximalIndependentSets
        = new HashSet<>();
 
    static Map<int[], Boolean> edges = new HashMap<>();
    static List<Integer> vertices = new ArrayList<>();
 
    // Function to print all independent sets
    static void printAllIndependentSets()
    {
        for (Set<Integer> set : independentSets) {
            System.out.print("{ ");
            for (int vertex : set) {
                System.out.print(vertex + " ");
            }
            System.out.print("}");
        }
        System.out.println();
    }
 
    // Function to extract all maximal independent sets
    static void printMaximalIndependentSets()
    {
        int maxCount = 0;
        int localCount;
        for (Set<Integer> set : independentSets) {
            localCount = 0;
            for (int vertex : set) {
                localCount++;
            }
            if (localCount > maxCount) {
                maxCount = localCount;
            }
        }
        for (Set<Integer> set : independentSets) {
            localCount = 0;
            Set<Integer> tempMaximalSet = new HashSet<>();
            for (int vertex : set) {
                localCount++;
                tempMaximalSet.add(vertex);
            }
            if (localCount == maxCount) {
                maximalIndependentSets.add(
                    Collections.unmodifiableSet(
                        tempMaximalSet));
            }
        }
        for (Set<Integer> set : maximalIndependentSets) {
            System.out.print("{ ");
            for (int vertex : set) {
                System.out.print(vertex + " ");
            }
            System.out.print("}");
        }
        System.out.println();
    }
 
    // Function to check if a node is safe node.
    static boolean
    isSafeForIndependentSet(int vertex,
                            Set<Integer> tempSolutionSet)
    {
        for (int node : tempSolutionSet) {
            if (edges.get(new int[] { node, vertex })
                != null) {
                return false;
            }
        }
        return true;
    }
 
    // Recursive function to find all independent sets
    static void
    findAllIndependentSets(int currV, int setSize,
                           Set<Integer> tempSolutionSet)
    {
        for (int i = 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(
            new HashSet<>(tempSolutionSet)));
    }
 
    // Driver Program
    public static void main(String[] args)
    {
        int V = 3, E = 2;
 
        for (int i = 1; i <= V; i++) {
            vertices.add(i);
        }
 
        List<int[]> inputEdges = new ArrayList<>();
        inputEdges.add(new int[] { 1, 2 });
        inputEdges.add(new int[] { 2, 3 });
 
        for (int i = 0; i < E; i++) {
            if (i < inputEdges.size()) {
                edges.put(inputEdges.get(i), true);
                edges.put(
                    new int[] { inputEdges.get(i)[1],
                                inputEdges.get(i)[0] },
                    true);
            }
        }
 
        Set<Integer> tempSolutionSet = new HashSet<>();
        findAllIndependentSets(1, V, tempSolutionSet);
 
        printAllIndependentSets();
 
        printMaximalIndependentSets();
    }
}


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()


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    // Define the independent sets and maximal independent sets as SortedSet of SortedSet
    static SortedSet<SortedSet<int>> independentSets = new SortedSet<SortedSet<int>>(new ComparerForSets());
    static SortedSet<SortedSet<int>> maximalIndependentSets = new SortedSet<SortedSet<int>>(new ComparerForSets());
 
    // Define the edges as a Dictionary with Tuple as key and int as value
    static Dictionary<Tuple<int, int>, int> edges = new Dictionary<Tuple<int, int>, int>();
 
    // Define the vertices as a List of int
    static List<int> vertices = new List<int>();
 
    static void Main()
    {
        // Define the number of vertices and edges
        int V = 3, E = 0;
 
        // Add the vertices to the vertices list
        for (int i = 1; i <= V; i++)
            vertices.Add(i);
 
        // Define the input edges as a List of Tuple
        List<Tuple<int, int>> inputEdges = new List<Tuple<int, int>>();
        Tuple<int, int> edge;
 
        // Add the edges to the edges dictionary
        for (int i = 0; i < E; i++)
        {
            Console.WriteLine(i);
            edge = Tuple.Create(inputEdges[i].Item1, inputEdges[i].Item2);
            edges[edge] = 1;
            int t = edge.Item1;
            edge = Tuple.Create(edge.Item2, t);
            edges[edge] = 1;
        }
 
        // Define the temporary solution set as a SortedSet
        SortedSet<int> tempSolutionSet = new SortedSet<int>();
 
        // Find all independent sets
        findAllIndependentSets(1, V, tempSolutionSet);
 
        // Print all independent sets and maximal independent sets
        printAllIndependentSets();
        printMaximalIndependentSets();
    }
 
    // Method to print all independent sets
    static void printAllIndependentSets()
    {
        foreach (var iter in independentSets)
        {
            Console.Write("{ ");
            foreach (var iter2 in iter)
            {
                Console.Write(iter2 + " ");
            }
            Console.Write("}");
        }
        Console.WriteLine();
    }
 
    // Method to print maximal independent sets
    static void printMaximalIndependentSets()
    {
        int maxCount = 0;
        int localCount = 0;
        foreach (var iter in independentSets)
        {
            localCount = 0;
            foreach (var iter2 in iter)
            {
                localCount++;
            }
            if (localCount > maxCount)
                maxCount = localCount;
        }
        foreach (var iter in independentSets)
        {
            localCount = 0;
            SortedSet<int> tempMaximalSet = new SortedSet<int>();
            foreach (var iter2 in iter)
            {
                localCount++;
                tempMaximalSet.Add(iter2);
            }
            if (localCount == maxCount)
                maximalIndependentSets.Add(tempMaximalSet);
        }
        foreach (var iter in maximalIndependentSets)
        {
            Console.Write("{ ");
            foreach (var iter2 in iter)
            {
                Console.Write(iter2 + " ");
            }
            Console.Write("}");
        }
        Console.WriteLine();
    }
 
    // Method to check if a vertex is safe for independent set
    static bool isSafeForIndependentSet(int vertex, SortedSet<int> tempSolutionSet)
    {
        foreach (var iter in tempSolutionSet)
        {
            if (edges.ContainsKey(Tuple.Create(iter, vertex)))
            {
                return false;
            }
        }
        return true;
    }
 
    // Method to find all independent sets
    static void findAllIndependentSets(int currV, int setSize, SortedSet<int> tempSolutionSet)
    {
        for (int i = currV; i <= setSize; i++)
        {
            if (isSafeForIndependentSet(vertices[i - 1], tempSolutionSet))
            {
                tempSolutionSet.Add(vertices[i - 1]);
                findAllIndependentSets(i + 1, setSize, new SortedSet<int>(tempSolutionSet));
                tempSolutionSet.Remove(vertices[i - 1]);
            }
        }
        independentSets.Add(new SortedSet<int>(tempSolutionSet));
    }
}
 
// Class to compare sets for sorting
public class ComparerForSets : IComparer<SortedSet<int>>
{
    public int Compare(SortedSet<int> x, SortedSet<int> y)
    {
        if (x.Count != y.Count)
            return x.Count.CompareTo(y.Count);
 
        return String.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 graph
let independentSets = new Set();
 
// To store all maximal independent
// sets in the graph
let maximalIndependentSets = new Set();
 
let edges = {};
let vertices = [];
 
// Function to print all independent sets
function printAllIndependentSets() {
  for (let itr of independentSets) {
    process.stdout.write("{ ");
    for (let itr2 of itr) {
      process.stdout.write(itr2 + " ");
    }
    process.stdout.write("}");
  }
  console.log();
}
 
// Function to extract all
// maximal independent sets
function printMaximalIndependentSets() {
  let maxCount = 0;
  let localCount = 0;
  for (let itr of independentSets) {
    localCount = 0;
    for (let itr2 of itr) {
      localCount += 1;
    }
 
    if (localCount > maxCount) {
      maxCount = localCount;
    }
  }
 
  for (let itr of independentSets) {
    localCount = 0;
    let tempMaximalSet = new Set();
 
    for (let itr2 of itr) {
      localCount += 1;
      tempMaximalSet.add(itr2);
    }
 
    if (localCount == maxCount) {
      maximalIndependentSets.add(new Set(tempMaximalSet));
    }
  }
 
  for (let itr of maximalIndependentSets) {
    process.stdout.write("{ ");
    for (let itr2 of itr) {
      process.stdout.write(itr2 + " ");
    }
    process.stdout.write("}");
  }
  console.log();
}
 
// Function to check if a
// node is safe node.
function isSafeForIndependentSet(vertex, tempSolutionSet) {
  for (let itr of tempSolutionSet) {
    if (edges[[itr, vertex]]) {
      return false;
    }
  }
 
  return true;
}
 
// Recursive function to find
// all independent sets
function findAllIndependentSets(currV, setSize, tempSolutionSet) {
  for (let i = 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(new Set(tempSolutionSet));
}
 
// Driver Program
let V = 3;
let E = 0;
 
for (let i = 1; i <= V; i++) {
  vertices.push(i);
}
 
let inputEdges = [];
 
for (let i = 0; i < E; i++) {
  edges[[inputEdges[i][0], inputEdges[i][1]]] = true;
  edges[[inputEdges[i][1], inputEdges[i][0]]] = true;
}
 
let tempSolutionSet = new Set();
 
findAllIndependentSets(1, V, tempSolutionSet);
 
printAllIndependentSets();
 
printMaximalIndependentSets();
 
// Expected output:
// { 1 }
// { 2 }
// { 3 }
// { 1 3 }
// { 1 2 }
// { 2 3 }
// { 1 2 3 }


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)



Last Updated : 15 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads