Find if an undirected graph contains an independent set of a given size in Python

An independent set in an undirected graph is a set of vertices where no two vertices are adjacent (directly connected by an edge). This article demonstrates how to find if a graph contains an independent set of a given size using Python.

We need to check whether a graph contains an independent set of size k. If such a set exists, return "Yes", otherwise "No".

Problem Understanding

Given an undirected graph represented as an adjacency matrix, we want to find k vertices such that none of them are connected to each other. For example, if k = 4, we need to find 4 vertices with no edges between any pair.

0 1 2 3 4 Sample Graph

Algorithm Approach

We use a recursive backtracking approach that tries all possible combinations of vertices and checks if they form a valid independent set.

Helper Function: is_valid()

This function checks if a given set of vertices forms an independent set by verifying no edges exist between any pair ?

def is_valid(graph, arr):
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if graph[arr[i]][arr[j]] == 1:
                return False
    return True

Main Function: solve()

This recursive function explores all possible combinations of vertices to find an independent set of size k ?

def solve(graph, arr, k, index, sol):
    if k == 0:
        if is_valid(graph, arr):
            sol[0] = True
            return
    else:
        if index >= 0:
            # Include current vertex
            solve(graph, arr + [index], k-1, index-1, sol)
            # Exclude current vertex  
            solve(graph, arr, k, index-1, sol)

Complete Implementation

def is_valid(graph, arr):
    """Check if given vertices form an independent set"""
    for i in range(len(arr)):
        for j in range(i + 1, len(arr)):
            if graph[arr[i]][arr[j]] == 1:
                return False
    return True

def solve(graph, arr, k, index, sol):
    """Find independent set of size k using backtracking"""
    if k == 0:
        if is_valid(graph, arr):
            sol[0] = True
            return
    else:
        if index >= 0:
            # Include current vertex
            solve(graph, arr + [index], k-1, index-1, sol)
            # Exclude current vertex
            if not sol[0]:  # Optimization: stop if solution found
                solve(graph, arr, k, index-1, sol)

# Example graph as adjacency matrix
graph = [
    [0, 1, 0, 0, 0],
    [1, 0, 1, 1, 1], 
    [0, 1, 0, 0, 0],
    [0, 1, 0, 0, 0],
    [0, 1, 0, 0, 0]
]

k = 4
sol = [False]
solve(graph, [], k, len(graph)-1, sol)

if sol[0]:
    print("Yes")
else:
    print("No")
Yes

How It Works

The algorithm works by:

  • Backtracking: Tries including/excluding each vertex
  • Validation: Checks if selected vertices have no edges between them
  • Base case: When k = 0, validates the current selection
  • Recursion: Explores all possible combinations systematically

Time Complexity

The time complexity is O(2^n × k^2) where n is the number of vertices, as we explore all possible subsets and validate each one.

Conclusion

This backtracking approach systematically explores all possible vertex combinations to find an independent set of the required size. While not the most efficient for large graphs, it provides a clear solution for the independent set problem.

Updated on: 2026-03-25T09:39:07+05:30

394 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements