- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find if an undirected graph contains an independent set of a given size in Python
Suppose we have a given undirected graph; we have to check whether it contains an independent set of size l. If there is any independent set of size l then return Yes otherwise No.
We have to keep in mind that an independent set in a graph is defined as a set of vertices which are not directly connected to each other.
So, if the input is like L = 4,
then the output will be yes
To solve this, we will follow these steps −
Define a function is_valid() . This will take graph, arr
for i in range 0 to size of arr, do
for j in range i + 1 to size of arr, do
if graph[arr[i], arr[j]] is same as 1, then
return False
return True
Define a function solve() . This will take graph, arr, k, index, sol
if k is same as 0, then
if is_valid(graph, arr) is same as True, then
sol[0] := True
return
otherwise,
if index >= k, then
return(solve(graph, arr[from index 0 to end] concatenate a list with [index], k-1, index-1, sol) or solve(graph, arr[from index 0 to end], k, index-1, sol))
otherwise,
return solve(graph, arr[from index 0 to end] concatenate a list with [index], k-1, index-1, sol)
Example
Let us see the following implementation to get better understanding −
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 def solve(graph, arr, k, index, sol): if k == 0: if is_valid(graph, arr) == True: sol[0] = True return else: if index >= k: return (solve(graph, arr[:] + [index], k-1, index-1, sol) or solve(graph, arr[:], k, index-1, sol)) else: return solve(graph, arr[:] + [index], k-1, index-1, sol) graph = [ [1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]] k = 4 arr = [] sol = [False] solve(graph, arr[:], k, len(graph)-1, sol) if sol[0]: print("Yes") else: print("No")
Input
[[1, 1, 0, 0, 0], [1, 1, 1, 1, 1], [0, 1, 1, 0, 0], [0, 1, 0, 1, 0], [0, 1, 0, 0, 1]], 4
Output
Yes