Electromagnetic Moat


In [4]:
bricks = []
with open('input.txt', 'rt') as f_input:
    for line in f_input:
        br = tuple(map(int, line.rstrip().split('/')))
        bricks.append(br)

Part 1


In [34]:
def bridges(bricks):
    queue = [([br], br[not br.index(0)]) for br in bricks if 0 in br]
    max_score = 0
    while queue:
        bridge, head = queue.pop(0)
        extended = False
        for br in bricks:
            if (br not in bridge) and (head in br):
                extended = True
                new_bridge = bridge[:] + [br]
                new_head = br[not br.index(head)]
                queue.append((new_bridge, new_head))
        if not extended:
            score = sum(map(sum, bridge))
            if score > max_score: 
                max_score = score
                max_score_bridge = bridge[:]
    return max_score, max_score_bridge

In [35]:
max_score, max_score_bridge = bridges(bricks)

In [36]:
print(max_score_bridge)


[(0, 39), (39, 30), (30, 35), (41, 35), (32, 41), (3, 32), (17, 3), (46, 17), (46, 50), (41, 50), (49, 41), (49, 4), (4, 30), (44, 30), (40, 44), (23, 40), (38, 23), (38, 20), (20, 24), (24, 14), (14, 45), (47, 45), (47, 11), (45, 11), (45, 50), (50, 36), (36, 31), (5, 31), (5, 5), (44, 5), (29, 44), (29, 29), (29, 12)]

In [37]:
print(max_score)


2006

Part 2


In [76]:
import operator

def longest_bridge(bricks):
    queue = [([br], br[not br.index(0)]) for br in bricks if 0 in br]
    max_len_strength = (1, 0)
    while queue:
        bridge, head = queue.pop(0)
        extended = False
        for br in bricks:
            if (br not in bridge) and (head in br):
                extended = True
                new_bridge = bridge[:] + [br]
                new_head = br[not br.index(head)]
                queue.append((new_bridge, new_head))
        if not extended:
            length = len(bridge)
            strength = sum(map(sum, bridge))
            if (length, strength) > max_len_strength:
                max_len_strength = (length, strength)
                max_score_bridge = bridge[:]
    return max_len_strength, max_score_bridge

Solution


In [77]:
max_score, max_score_bridge = longest_bridge(bricks)

In [78]:
print(max_score)


(34, 1994)

In [79]:
print(max_score_bridge)


[(0, 39), (39, 30), (30, 35), (41, 35), (32, 41), (3, 32), (17, 3), (2, 17), (2, 31), (36, 31), (50, 36), (41, 50), (49, 41), (49, 4), (4, 30), (44, 30), (44, 5), (5, 5), (5, 37), (20, 37), (38, 20), (38, 23), (23, 40), (40, 24), (24, 14), (14, 45), (47, 45), (47, 11), (45, 11), (45, 50), (46, 50), (46, 17), (22, 17), (22, 48)]