Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
depth-first search solution in Clear category for How to Find Friends by David_Jones
from collections import defaultdict
def check_connection(network, first, second):
friends = defaultdict(set)
for connection in network:
name_1, name_2 = connection.split('-')
friends[name_1].add(name_2)
friends[name_2].add(name_1)
visited = set()
stack = [first]
while stack:
name = stack.pop()
if name == second:
return True
visited.add(name)
for friend in friends[name]:
if friend not in visited:
stack.append(friend)
return False
May 14, 2019
Comments: