def connected_components(g): vertices = g.vertices components = vertices s = dsf.DSF(vertices) for edge in g.el: components -= s.union(edge.source,edge.dest) return components
def kruskal(G,trace=False): weight_heap = min_heap.MinHeap() S = dsf.DSF(len(G.al)) for v in range(len(G.al)): for edge in G.al[v]: if v<edge.dest: weight_heap.insert(min_heap.HeapRecord(edge.weight,[v,edge.dest,edge.weight])) mst = graph.Graph(len(G.al),weighted=True) count = 0 while count<len(G.al)-1 and len(weight_heap.heap)>0: next_edge = weight_heap.extractMin().data if S.union(next_edge[0],next_edge[1])==1: mst.insert_edge(next_edge[0],next_edge[1],next_edge[2]) count+=1 if trace: draw_over(G,mst,'Kruskal '+str(count)) print(next_edge,'added to mst') else: if trace: print(next_edge,'rejected') if count == len(G.al)-1: return mst print('Graph has no minimum spanning tree') return None
def connected_components(g): vertices = len(g.al) components = vertices s = dsf.DSF(vertices) for v in range(vertices): for edge in g.al[v]: components -= s.union(v, edge.dest) return components
def connected_components(G, trace=False): # Returns the disjoint set forest representing the connected components of G S = dsf.DSF(len(G.al)) for v in range(len(G.al)): for edge in G.al[v]: if v < edge.dest: S.union(v, edge.dest) if trace: print('last edge: ({},{})'.format(v, edge.dest)) print('dsf:', S.parent) return S
def connected_components(g): vertices = len(g.al) components = vertices s = dsf.DSF(vertices) for v in range(vertices): for edge in g.al[v]: components -= s.union(v, edge.dest) s.draw() if components > 1: return True return False
for i in s.set_list(): if v in i and len(i) == 1: return True return False def is_compressed(s): for i in s.parent: if i != -1 and s.parent[i] != -1: return False return True if __name__ == "__main__": plt.close("all") s = dsf.DSF(8) s.union(0, 1) print(s.parent) print(is_compressed(s)) # True s.draw() s.union(7, 2) print(s.parent) print(is_compressed(s)) # True s.draw() s.union(3, 5) print(s.parent) print(is_compressed(s)) # True s.draw()
g.insert_edge(0,1) g.insert_edge(0,2) g.insert_edge(1,2) g.insert_edge(1,3) g.insert_edge(2,3) g.insert_edge(3,4) g.insert_edge(4,1) g.display() g.draw('Question 6') p = bfs(g) for i in range(5): print('vertex',i,'distance from source',dist_from_prev(p,i)) print('\n *********** Question 7 **************') s = dsf.DSF(6) s.union(0,1) s.union(4,2) s.union(3,1) print(s.parent) s.draw('Question 7') for i in range(6): print('element',i,' elements in same set:',in_same_set(s,i)) print('\n *********** Question 8 **************') s = [2,5,7,11,14,-6,-10] for i in range(-10,10): print('goal:',i,'subset:',subsetsum(s,i,sum(s)))