Advertisement
Iam_Sandeep

bipartite graph

Jun 5th, 2021 (edited)
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. """
  2. algorithm:bfs
  3. method: check whether vertex coloring==2?
  4. -1------------------------->not visited
  5. 0 -------------------------> color 1
  6. 1-------------------------->color 2
  7. """
  8.  
  9.  
  10. from collections import deque
  11. class Solution:
  12.    
  13.     def isBipartite(self, V, adj):
  14.         def bfs(src):
  15.             q=deque()
  16.             q.append(src)
  17.             col[src]=0
  18.             while q:
  19.                 t=q.popleft()
  20.                 for i in adj[t]:
  21.                     if i==t:
  22.                         return False
  23.                     elif col[i]==-1:
  24.                         col[i]=1-col[t]
  25.                         q.append(i)
  26.                     elif col[i]==col[t]:
  27.                         return False
  28.             return True
  29.  
  30.         #code here
  31.         col=[-1]*V
  32.         for i in range(V):
  33.             if col[i]==-1 and not bfs(i):
  34.                 return False
  35.         return True
  36. '''
  37. DFS version
  38. '''
  39. class Solution:
  40.     def isBipartite(self, n, adj):
  41.         cols=[-1]*n
  42.         def dfs(u):
  43.             for v in adj[u]:
  44.                 if cols[v]!=-1:#if unvisited
  45.                     if cols[v]==cols[u]:
  46.                         return False
  47.                 else:#if visited
  48.                     cols[v]=1-cols[u]
  49.                     if dfs(v)==False:return False
  50.             return True
  51.         for i in range(n):
  52.             if cols[i]==-1:
  53.                 cols[i]=0
  54.                 if dfs(i)==False:return 0
  55.         return 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement