#!/usr/bin/env python3 import sys input_file = sys.argv[1] with open(input_file) as fd: lines = [line.rstrip() for line in fd.readlines()] height = len(lines) width = len(lines[0]) tmap: list[list[int]] = [[int(a) for a in line] for line in lines] directions = [ (0, 1), (0, -1), (1, 0), (-1, 0), ] def print_path(path: list[tuple[int, int]]) -> None: viz = [["."] * width for _ in range(height)] for c, pos in enumerate(path): i, j = pos viz[i][j] = str(c) for line in viz: print("".join(line)) print() def score(pos: tuple[int, int], path: list[tuple[int, int]]) -> set[tuple[int, int]]: path = path + [pos] i, j = pos c = tmap[i][j] if c == 9: return {pos} reachable = set() for direction in directions: ii, jj = i + direction[0], j + direction[1] if ii not in range(height) or jj not in range(width): continue cc = tmap[ii][jj] if cc != c + 1: continue reachable |= score((ii, jj), path) return reachable tscore = 0 for i in range(height): for j in range(width): c = tmap[i][j] if c != 0: continue cscore = len(score((i, j), [])) # print(i, j, cscore) tscore += cscore print(tscore)