import matrix from pprint import pprint import shared DIRS = { 'N': (-1,0), 'S': (1, 0), 'W': (0,-1), 'E': (0, 1), } EXITS = { '│': ['N', 'S'], '─': ['E', 'W'], '└': ['N', 'E'], '┘': ['N', 'W'], '┐': ['S', 'W'], '┌': ['S', 'E'], } TRANSLATE = { "F":"┌", "-":"─", "7":"┐", "|":"│", "L":"└", "J":"┘", } OTHER = { '.': None, 'S': "?" } OPPOSITES = { "N": "S", "S": "N", "W": "E", "E": "W", } def find_connected_neighbors(mat, y, x): exits = {} neighbors = {k:v for k,v in matrix.get_neighbors_cardinal(mat, x, y, False).items() if v['value'] in EXITS.keys()} for _dir, value in neighbors.items(): _char = value["value"] r = value["r"] c = value["c"] if OPPOSITES[_dir] in EXITS[_char]: exits[_dir] = ((r,c), _char) return exits def get_exits(mat, r, c): sym = mat[r][c] return EXITS[sym] def next_coords(r, c, _exit): d = DIRS[_exit] r += d[0] c += d[1] return (r,c) # @shared.profile def part1(mat): for k,v in TRANSLATE.items(): coords = matrix.find_in_matrix(mat,k, one=False) for r,c in coords: mat[r][c]=v Sy, Sx = matrix.find_in_matrix(mat, "S") cursor = (Sy,Sx) seen = [] neighbors = find_connected_neighbors(mat, *cursor) EXITS["S"] = list(neighbors.keys()) cursor, mat, seen, x = loop(cursor, mat, seen) matrix.highlight(mat, red=seen, green=[seen[0]]) print(x//2) def loop(cursor, mat, seen): x = 0 while True: x += 1 seen.append(cursor) exits = get_exits(mat, *cursor) # print(cursor, seen, exits) # mat[cursor[0]][cursor[1]]="x" # print(matrix.ppmx(mat, pad=False, space=False)) # matrix.highlight(mat, red=seen) for e in exits: _next = next_coords(*cursor, e) if _next in seen: # print("seen", e, _next) continue # print(exits, "next exit", e, _next) break else: return cursor, mat, seen, x cursor = _next # print(neighbors) # for cd, coord_sym in neighbors.items(): # coord, _ = coord_sym # if coord in seen: # continue # seen.append(coord) # cursor = coord # neighbors = find_connected_neighbors(mat, cursor[0], cursor[1]) # break # mat[cursor[0]][cursor[1]]="x" # print(matrix.ppmx(mat, pad=True, space=False)) # @shared.profile def part2(mat): pass def main(): mat = shared.load_file_char_matrix(shared.get_fname(10)) with shared.elapsed_timer() as elapsed: part1(mat) print("🕒", elapsed()) with shared.elapsed_timer() as elapsed: part2(mat) print("🕒", elapsed()) if __name__ == "__main__": main()