@@ -0,0 +1,1516 @@
+from collections import deque%0Afrom itertools import combinations, permutations%0A%0A%0Adef steps(board, pos, target):%0A    def _nextpos((x, y)):%0A        for dx, dy in %5B(-1, 0), (1, 0), (0, 1), (0, -1)%5D:%0A            if board%5By + dy%5D%5Bx + dx%5D != '#':%0A                yield (x + dx, y + dy)%0A    seen = set()%0A    steps = 0%0A    states = deque(%5Bpos%5D)%0A    while True:%0A        steps += 1%0A        nextstates = %5B%5D%0A        for currstate in states:%0A            for nextpos in _nextpos(currstate):%0A                if nextpos == target:%0A                    return steps%0A                if nextpos in seen:%0A                    continue%0A                seen.add(nextpos)%0A                nextstates.append(nextpos)%0A        states = nextstates%0A%0A%0Adef _permute(digits, part=2):%0A    for p in permutations(digits - %7B'0'%7D):%0A        if part == 2:%0A            yield '0' + ''.join(p) + '0'%0A        elif part == 1:%0A            yield '0' + ''.join(p)%0A%0A%0Adef p1(lines, part=2):%0A    board = %5Bl.strip() for l in lines%5D%0A    digits = %7Bx for x in ''.join(board) if x.isdigit()%7D%0A    pos = %7B%7D%0A    for y, l in enumerate(board):%0A        for d in digits:%0A            if d in l:%0A                pos%5Bd%5D = l.index(d), y%0A    s = %7B%7D%0A    for start, end in combinations(digits, 2):%0A        s%5Bstart, end%5D = s%5Bend, start%5D = steps(board, pos%5Bstart%5D, pos%5Bend%5D)%0A%0A    return min(%0A        sum(s%5Ba, b%5D for a, b in zip(p, p%5B1:%5D))%0A        for p in _permute(digits, part=part))%0A%0A# with open('example_24.txt') as f:%0A#     print p1(f)%0A%0Awith open('input_24.txt') as f:%0A    print p1(f)%0A

day 24