Advertisement
Guest User

Untitled

a guest
Feb 21st, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. class Solution:
  2.     '''
  3.    [[1,2,3], [0,2], [0,1,3], [0,2]]
  4.    [[],[2,4,6],[1,4,8,9],[7,8],[1,2,8,9],[6,9],[1,5,7,8,9],[3,6,9],[2,3,4,6,9],[2,4,5,6,7,8]]
  5.    [[1, 3],[0, 2],[1, 3],[0, 2]]
  6.    '''
  7.     def verify_bipartite_graph(self, graph, group_dict, curr_id, group_id):
  8.        
  9.         group_dict[group_id].add(curr_id)
  10.        
  11.         for neighbor in graph[curr_id]:
  12.             if neighbor in group_dict[group_id]:
  13.                 return False # same color
  14.             if neighbor not in group_dict[-1 * group_id]: # unvisited , paint opposite color
  15.                 if not self.verify_bipartite_graph(graph, group_dict, neighbor, -1 * group_id):
  16.                     return False
  17.        
  18.         # visited = len(group_dict[1]) + len(group_dict[-1])
  19.         # return visited == len(graph)
  20.         return True
  21.        
  22.     def isBipartite(self, graph):
  23.         """
  24.        :type graph: List[List[int]]
  25.        :rtype: bool
  26.        """
  27.         groups = {1 : set(), -1 : set()}
  28.         #return self.verify_bipartite_graph(graph, groups, 0, 1) <- old code
  29.         #--->
  30.         for i in range(len(graph)):
  31.             if not self.verify_bipartite_graph(graph, groups, i, 1):
  32.                 return False
  33.         return True
  34.         #<----
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement