写的有点快,有时间翻回来再深入理解下
data=‘‘‘0 1 2 3 4 1 3 5 1 5 7 6 8 6 0 5 1 3‘‘‘ lines=data.split("\n") group=[0,1,2,3,4,5,6,7,8,9] def get_root(v): if group[v]==v: return v else: group[v]=get_root(group[v]) return group[v] for i in range(len(group)): for line in lines: a,b=map(int,line.split(" ")) a=get_root(a) b=get_root(b) if a!=b: group[b]=a print(group)
原文:https://www.cnblogs.com/shitianfang/p/12426262.html