Maximal independent set from a given Graph using Backtracking
Last Updated :
21 Jul, 2024
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
#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();
}
}
Python
# 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)
Similar Reads
Find maximum matching in a given Binary Tree
Given a Tree with N nodes values from 1 to N and N - 1 edges. The task is to find the maximum matching in the given tree. A matching in a tree is a collection of edges such that no pair of edges share a common node. Matching with the most edges is known as a maximum matching. Examples: Input: Below
14 min read
Largest sub-set possible for an array satisfying the given condition
Given an array arr[] and an integer K. The task is to find the size of the maximum sub-set such that every pair from the sub-set (X, Y) is of the form Y != (X * K) where X < Y. Examples: Input: arr[] = {2, 3, 6, 5, 4, 10}, K = 2 Output: 3 {2, 3, 5} is the required sub-set Input: arr[] = {1, 2, 3,
5 min read
How to Find the Maximum Key in a Map in C++?
In C++, the Standard Template Library (STL) provides a map container to store elements in a mapped fashion so each element has a key value and a mapped value. In this article, we will see how to find the maximum key in a map in C++. Example: Input : myMap : {{1, 10}, {2, 20}, {4, 12}, {3, 44}}Output
2 min read
Minimum value of distance of farthest node in a Graph
Given an acyclic undirected graph having N nodes and N-1 edges in the form of a 2D array arr[][] in which every row consists of two numbers L and R which denotes the edge between L and R. For every node X in the tree, let dis(X) denotes the number of edges from X to the farthest node. The task is to
11 min read
Maximum OR value of a pair in an Array | Set 2
Given an array arr[] of N positive elements, the task is to find the maximum bitwise OR value of a pair from the given array.Examples: Input: arr[] = {3, 6, 8, 16} Output: 24 Explanation: The pair giving maximum OR value is (8, 16) 8|16 = 24Input: arr[] = {8, 7, 3, 12} Output: 15 Explanation: There
5 min read
C++ Program For Pointing Arbit Pointer To Greatest Value Right Side Node In A Linked List
Given singly linked list with every node having an additional âarbitraryâ pointer that currently points to NULL. We need to make the âarbitraryâ pointer to the greatest value node in a linked list on its right side. A Simple Solution is to traverse all nodes one by one. For every node, find the node
5 min read
Maximum number of edges among all connected components of an undirected graph
Given integers 'N' and 'K' where, N is the number of vertices of an undirected graph and 'K' denotes the number of edges in the same graph (each edge is denoted by a pair of integers where i, j means that the vertex 'i' is directly connected to the vertex 'j' in the graph). The task is to find the m
6 min read
How to Find the Last Occurrence of an Element in a Set in C++?
In C++, a set is a container that stores unique elements in a sorted order and elements are accessed and traversed using iterators. In this article, we will learn how to find the last occurrence of a specific element in a set in C++. Example Input:set<int> s = {1, 2, 3, 4, 5, 6, 7, 8, 9}; Key
2 min read
Largest connected component on a grid
Given a grid with different colors in a different cell, each color represented by a different number. The task is to find out the largest connected component on the grid. Largest component grid refers to a maximum set of cells such that you can move from any cell to any other cell in this set by onl
15+ min read
C++ Program to Solve the 0-1 Knapsack Problem
Prerequisite: Introduction to Knapsack Problem, its Types and How to solve them The 0-1 Knapsack Problem is a classic problem in dynamic programming. For a given set of N items, each having a weight and a value, and a knapsack (a bag that can hold at most W weight inside it) with a maximum weight ca
9 min read