Advent of Code: Day 12

For Day 12, the challenge is to count the number of isolated groups within a graph. My Python solution is below:

connections = {}

with open("input.txt", "r") as o:
    for line in o.read().split("\n"):
        p = line.split(" <-> ")
        connections[int(p[0])] = [int(i.strip()) for i in p[1].split(",")]

groups = {}
marked = []

def check(ptr, group=None):
    if ptr in marked:
        return
    marked.append(ptr)

    if group is None:
        group = ptr
        groups[group] = []

    groups[group].append(ptr)

    for c in connections[ptr]:
        check(c, group)

for i in connections.keys():
    check(i)

print "Part 1:", len(groups[0])
print "Part 2:", len(groups)

I found this one to be significantly easier than recent days.

Advent of Code runs every day up to Christmas, you should join in!.

Show Comments

Get the latest posts delivered right to your inbox.