Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
UnionFind solution in Clear category for How to Find Friends by veky
def check_connection(network, first, second):
from collections import Counter
component, rank = {}, Counter()
def find(x):
if component.setdefault(x, x) != x:
component[x] = find(component[x])
return component[x]
for edge in network:
xr, yr = map(find, edge.split("-"))
if rank[xr] < rank[yr]:
component[xr] = yr
else:
component[yr] = xr
rank[xr] += rank[xr] == rank[yr]
return find(first) == find(second)
June 4, 2014
Comments: