Skip to content

Graphs · routine

Separate groups

Friendships go both ways: graph maps each person to their friends, and if a lists b then b lists a. Write components(graph) returning how many separate friend groups there are.

Walk from anyone not yet seen, marking everyone you reach. Each fresh start is a new group.

Run adds print(components({"a": ["b"], "b": ["a"], "c": []})) after your code, to try it.

Stuck on the idea rather than the code? The Groups and orderings lesson walks through it.