import numpy as np file = "inputs/day9.input" numbers = [x.decode().replace("\n", "") for x in open(file, "rb").readlines()] numbers = [[int(x) for x in number] for number in numbers] numbers = np.array(numbers) coords = [] for x in range(numbers.shape[0]): for y in range(numbers.shape[1]): if x == 0 and y == 0: if numbers[x + 1, y] > numbers[x, y] and numbers[x, y + 1] > numbers[x, y]: coords.append((x, y)) elif x == 0 and y == numbers.shape[1] - 1: if numbers[x + 1, y] > numbers[x, y] and numbers[x, y - 1] > numbers[x, y]: coords.append((x, y)) elif x == numbers.shape[0] - 1 and y == 0: if numbers[x - 1, y] > numbers[x, y] and numbers[x, y + 1] > numbers[x, y]: coords.append((x, y)) elif x == numbers.shape[0] - 1 and y == numbers.shape[1] - 1: if numbers[x - 1, y] > numbers[x, y] and numbers[x, y - 1] > numbers[x, y]: coords.append((x, y)) elif x == 0 and y > 0 and y < numbers.shape[1] - 1: if ( numbers[x, y + 1] > numbers[x, y] and numbers[x, y - 1] > numbers[x, y] and numbers[x + 1, y] > numbers[x, y] ): coords.append((x, y)) elif x == numbers.shape[0] - 1 and y > 0 and y < numbers.shape[1] - 1: if ( numbers[x, y + 1] > numbers[x, y] and numbers[x, y - 1] > numbers[x, y] and numbers[x - 1, y] > numbers[x, y] ): coords.append((x, y)) elif y == 0 and x > 0 and x < numbers.shape[0] - 1: if ( numbers[x, y + 1] > numbers[x, y] and numbers[x - 1, y] > numbers[x, y] and numbers[x + 1, y] > numbers[x, y] ): coords.append((x, y)) elif y == numbers.shape[1] - 1 and x > 0 and x < numbers.shape[0] - 1: if ( numbers[x, y - 1] > numbers[x, y] and numbers[x - 1, y] > numbers[x, y] and numbers[x + 1, y] > numbers[x, y] ): coords.append((x, y)) else: if ( numbers[x, y - 1] > numbers[x, y] and numbers[x, y + 1] > numbers[x, y] and numbers[x - 1, y] > numbers[x, y] and numbers[x + 1, y] > numbers[x, y] ): coords.append((x, y)) def get_candidates(tup): candidates = [] x, y = tup if x != 0 and numbers[x - 1, y] != 9 and numbers[x - 1, y] > numbers[x, y]: candidates.append((x - 1, y)) if ( x != numbers.shape[0] - 1 and numbers[x + 1, y] != 9 and numbers[x + 1, y] > numbers[x, y] ): candidates.append((x + 1, y)) if y != 0 and numbers[x, y - 1] != 9 and numbers[x, y - 1] > numbers[x, y]: candidates.append((x, y - 1)) if ( y != numbers.shape[1] - 1 and numbers[x, y + 1] != 9 and numbers[x, y + 1] > numbers[x, y] ): candidates.append((x, y + 1)) return candidates def get_basin(tup): basin = [] starts = [tup] while len(starts) > 0: for start in starts: candidates = get_candidates(start) for candidate in candidates: if candidate not in basin and candidate not in starts: starts.append(candidate) basin.append(start) starts.remove(start) return basin basin_lengths = [] for coord in coords: basin_lengths.append(len(get_basin(coord))) lengths = sorted(basin_lengths) print(lengths[-3] * lengths[-2] * lengths[-1])