#!/usr/bin/env python # 2021 - Advent Of Code - 9 def parse_file(file): hmap = [] with open(file, encoding="utf-8") as f: for line in f.readlines(): linemap = [] for n in line.strip(): linemap.append(int(n)) hmap.append(linemap) return hmap def print_hmap(hmap): for y, _ in enumerate(hmap): for x, _ in enumerate(hmap[y]): print(hmap[y][x], end='') print() def find_lowpoints(hmap): # pylint: disable=R0912 lpoints = [] # first line x = 0 y = 0 if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y + 1][x]: lpoints.append([x, y]) for x in range(1, len(hmap[y]) - 1): v = hmap[y][x] if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y + 1][x]: lpoints.append([x, y]) x = len(hmap[y]) - 1 if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y + 1][x]: lpoints.append([x, y]) # middle lines for y in range(1, len(hmap) - 1): x = 0 if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y - 1][x] and hmap[y][x] < hmap[y + 1][x]: lpoints.append([x, y]) for x in range(1, len(hmap[y]) - 1): v = hmap[y][x] if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y - 1][x] and v < hmap[y + 1][x]: lpoints.append([x, y]) x = len(hmap[y]) - 1 if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y - 1][x] and hmap[y][x] < hmap[y + 1][x]: lpoints.append([x, y]) # last line y = len(hmap) - 1 x = 0 if hmap[y][x] < hmap[y][x + 1] and hmap[y][x] < hmap[y - 1][x]: lpoints.append([x, y]) for x in range(1, len(hmap[y]) - 1): v = hmap[y][x] if v < hmap[y][x - 1] and v < hmap[y][x + 1] and v < hmap[y - 1][x]: lpoints.append([x, y]) x = len(hmap[y]) - 1 if hmap[y][x] < hmap[y][x - 1] and hmap[y][x] < hmap[y - 1][x]: lpoints.append([x, y]) return lpoints # heightmap = parse_file('input_example.txt') heightmap = parse_file('input.txt') # print_hmap(heightmap) low_points = find_lowpoints(heightmap) risk_levels = 0 for p in low_points: print(f'low point at {p}, value {heightmap[p[1]][p[0]]}') risk_levels += heightmap[p[1]][p[0]] + 1 print(f'The sum of risk levels is {risk_levels}')