|
| 1 | +from aoc import * |
| 2 | +import sys |
| 3 | + |
| 4 | + |
| 5 | +DIRS = ((-1, 0), (0, 1), (1, 0), (0, -1)) |
| 6 | + |
| 7 | + |
| 8 | +def search(i, j, m, lengths, length): |
| 9 | + """ |
| 10 | + :param lengths: lengths from the end |
| 11 | + """ |
| 12 | + togo = [] |
| 13 | + for d in DIRS: |
| 14 | + pos = i + d[0], j + d[1] |
| 15 | + if ( |
| 16 | + pos in m |
| 17 | + and m[pos] in '.SE' |
| 18 | + and (pos not in lengths or lengths[pos] > length + 1) |
| 19 | + ): |
| 20 | + lengths[pos] = length + 1 |
| 21 | + togo.append(pos) |
| 22 | + for pos in togo: |
| 23 | + search(*pos, m, lengths, length + 1) |
| 24 | + |
| 25 | + |
| 26 | +def main(infi: str): |
| 27 | + sys.setrecursionlimit(10000) |
| 28 | + inp = load_map_dd(infi) |
| 29 | + end = [(i, j) for (i, j), e in inp.items() if e == 'E'][0] |
| 30 | + lengths = {} |
| 31 | + search(*end, inp, lengths, 0) |
| 32 | + s = 0 |
| 33 | + for (i, j), e in inp.items(): |
| 34 | + if e == '#': |
| 35 | + connected = [ |
| 36 | + (i + d[0], j + d[1]) |
| 37 | + for d in DIRS |
| 38 | + if (i + d[0], j + d[1]) in inp |
| 39 | + and inp[i + d[0], j + d[1]] in '.SE' |
| 40 | + ] |
| 41 | + if len(connected) == 2: |
| 42 | + length = abs(lengths[connected[0]] - lengths[connected[1]]) - 2 |
| 43 | + if length >= 100: |
| 44 | + s += 1 |
| 45 | + elif len(connected) > 2: |
| 46 | + continue |
| 47 | + return s |
| 48 | + |
| 49 | + |
| 50 | +DAY = 20 |
| 51 | +FILE_TEST = f"{DAY}_testa.txt" |
| 52 | +# FILE_TEST = f"{DAY}_testb.txt" |
| 53 | +FILE_EXP = f"{DAY}_exp.txt" |
| 54 | +FILE = f"{DAY}.txt" |
| 55 | +# test_and_submit(main, FILE_TEST, FILE_EXP, FILE, DAY) |
| 56 | +# print(main(FILE_TEST)) |
| 57 | +print(main(FILE)) |
0 commit comments