def cycles(graph): union_find = UnionFind() new = {} for v in graph: new_edges = [] set_v = union_find.make_set(v) for u in graph[v]: new_edges.append(union_find.make_set(u)) new[set_v] = new_edges for u_ in new: for v_ in new[u_]: if union_find.find_set(u_) == union_find.find_set(v_): return True else: union_find.union(u_, v_) return False
def kruskals(graph): """ :param graph: undigraph :return: """ T = set() # empty edge set union_find = UnionFind() new = {} for v in graph: new_edges = [] set_v = union_find.make_set(v) for u, w in graph[v]: new_edges.append((union_find.make_set(u), w)) new[set_v] = new_edges edges = [(u, v[0], v[1]) for u in new for v in new[u]] edges.sort(key=lambda x: x[-1]) for u, v, _ in edges: if union_find.find_set(u) != union_find.find_set(v): T.add((union_find.get_key(u), union_find.get_key(v))) union_find.union(u, v) return T