Advertisement
serega1112

886

Mar 6th, 2021
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.81 KB | None | 0 0
  1. class Solution:
  2.     def possibleBipartition(self, N: int, dislikes: List[List[int]]) -> bool:
  3.        
  4.         g = defaultdict(list)
  5.         visited = defaultdict(int)
  6.         for a, b in dislikes:
  7.             g[a].append(b)
  8.             g[b].append(a)
  9.            
  10.        
  11.         for v in g:
  12.             if visited[v] == 0:
  13.                 st = [v]
  14.                 visited[v] = 1
  15.                 while st:
  16.                     cur = st.pop()
  17.                     color = 2 if visited[cur] == 1 else 1
  18.                     for n in g[cur]:
  19.                         if visited[n] == 0:
  20.                             visited[n] = color
  21.                             st.append(n)
  22.                         elif visited[n] != color:
  23.                             return False
  24.                    
  25.         return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement