Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to check whether given graph is bipartite or not in Python
A bipartite graph is an undirected graph where vertices can be divided into two disjoint sets such that no two vertices within the same set are adjacent. In other words, every edge connects vertices from different sets.
For example, if we have the following graph:
This graph is bipartite because vertices {0, 4} form set A and vertices {1, 2, 3} form set B, with all edges connecting vertices from different sets.
Algorithm Approach
We can use graph coloring with two colors to check if a graph is bipartite. If we can color all vertices using only two colors such that no adjacent vertices have the same color, then the graph is bipartite.
Implementation Using DFS
from collections import defaultdict
class Solution:
def solve(self, arr):
n = len(arr)
graph = [set() for i in range(n)]
# Build adjacency list
for i in range(n):
for j in arr[i]:
graph[j].add(i)
graph[i].add(j)
color = [-1] * n
result = [True]
def dfs(source):
for child in graph[source]:
if color[child] != -1:
if color[child] == color[source]:
result[0] = False
return
continue
color[child] = 1 - color[source]
dfs(child)
for i in range(n):
if color[i] == -1:
color[i] = 0 # Start coloring with 0
dfs(i)
return result[0]
# Test the implementation
ob = Solution()
graph = [[1,2,3],[0],[0,4],[0,4],[2,3]]
print(ob.solve(graph))
The output of the above code is ?
True
How It Works
The algorithm works as follows:
Graph Construction: Convert the adjacency list representation into a proper graph structure
Color Assignment: Use DFS to assign colors (0 or 1) to vertices
Conflict Detection: If any two adjacent vertices have the same color, the graph is not bipartite
Component Handling: Process all connected components in case of disconnected graphs
Alternative Implementation with BFS
from collections import deque
def is_bipartite_bfs(graph):
n = len(graph)
color = [-1] * n
for start in range(n):
if color[start] == -1:
queue = deque([start])
color[start] = 0
while queue:
node = queue.popleft()
for neighbor in graph[node]:
if color[neighbor] == -1:
color[neighbor] = 1 - color[node]
queue.append(neighbor)
elif color[neighbor] == color[node]:
return False
return True
# Test with same graph
graph = [[1,2,3],[0],[0,4],[0,4],[2,3]]
print(is_bipartite_bfs(graph))
The output of the above code is ?
True
Time and Space Complexity
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| DFS | O(V + E) | O(V) |
| BFS | O(V + E) | O(V) |
Where V is the number of vertices and E is the number of edges.
Conclusion
A graph is bipartite if and only if it can be colored using two colors such that no adjacent vertices share the same color. Both DFS and BFS approaches work efficiently with O(V + E) time complexity.
