imashutosh51

Bipartite Graph

Mar 22nd, 2026
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.97 KB | None | 0 0
  1. """
  2. Problem:
  3. Given a graph with v vertices and edge list, determine whether the graph
  4. is bipartite. A graph is bipartite if we can divide nodes into two groups
  5. such that no two adjacent nodes belong to the same group.
  6.  
  7. Intuition:
  8. We treat this as a 2-coloring problem using DFS.
  9. Instead of a visited array, we use a color array:
  10.    -1 → unvisited
  11.     0 → color A
  12.     1 → color B
  13.  
  14. We assign a color to a node and try to assign the opposite color to all
  15. its neighbors. If at any point a neighbor already has the same color as
  16. the current node, the graph is not bipartite.
  17.  
  18. This works because a valid bipartite graph can always be colored using
  19. two colors, and any conflict indicates an odd-length cycle.
  20.  
  21. Steps:
  22. 1. Build adjacency list from edges.
  23. 2. Initialize color array with -1.
  24. 3. Traverse all nodes (to handle disconnected graph):
  25.    - If node is unvisited, start DFS with color 0.
  26. 4. In DFS:
  27.    - Assign current color to node.
  28.    - For each neighbor:
  29.        a. If same color → return False.
  30.        b. If unvisited → recursively assign opposite color.
  31. 5. If all nodes are processed without conflict → return True.
  32.  
  33. Time Complexity: O(V + E)
  34. Space Complexity: O(V)
  35. """
  36. from collections import defaultdict
  37. def dfs(i,cur_color,graph,colors):
  38.     colors[i]=cur_color
  39.     for neigh in graph[i]:
  40.         if colors[neigh]==cur_color:
  41.             return False
  42.         if colors[neigh]==-1:
  43.             if cur_color==0 and not dfs(neigh,1,graph,colors):
  44.                 return False
  45.             elif cur_color==1 and not dfs(neigh,0,graph,colors):
  46.                 return False
  47.     return True
  48.        
  49.  
  50. class Solution:
  51.     def isBipartite(self, v, edges):
  52.         colors=[-1]*v
  53.         graph=defaultdict(list)
  54.         for a,b in edges:
  55.             graph[a].append(b)
  56.        
  57.         for i in range(v):
  58.             if colors[i]==-1: #not visited
  59.                 if dfs(i,0,graph,colors)==False:
  60.                     return False
  61.         return True
Advertisement
Add Comment
Please, Sign In to add comment