Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
[v2] Simple BFS with collections.defaultdict & deque solution in Clear category for How to Find Friends by Phil15
from collections import defaultdict, deque
def check_connection(network, first, second):
graph, queue, visited = defaultdict(set), deque([first]), set()
for relation in network:
a, b = relation.split('-')
graph[a].add(b)
graph[b].add(a)
while queue:
friend = queue.popleft()
if friend == second:
return True
visited.add(friend)
queue.extend(graph[friend] - visited)
return False
Sept. 22, 2019