2022 - Day 12 (Hill Climbing Algorithm)

View puzzle description on AdventOfCode.com
Part 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python3

#Advent of Code
#2022 Day 12, Part 1
#Solution by James C. (https://github.com/JamesMCo)

import os, sys
sys.path.append(os.path.abspath("../.."))
import unittest, util.read
from util.tests import run

import networkx as nx

def solve(puzzle_input):
    height = len(puzzle_input)
    width  = len(puzzle_input[0])

    def parse_space(space):
        match space:
            case "S":
                return 0
            case "E":
                return 25
            case letter:
                return ord(letter) - ord("a")

    start = None
    target = None
    for y, row in enumerate(puzzle_input):
        for x, col in enumerate(row):
            if col == "S":
                start = (x, y)
                if target != None:
                    break
            if col == "E":
                target = (x, y)
                if start != None:
                    break

    puzzle_input = [[parse_space(space) for space in row] for row in puzzle_input]

    def neighbours(x, y):
        # Returns in order up, right, down, left
        if y != 0:
            yield ((x, y - 1), puzzle_input[y - 1][x])
        if x != width - 1:
            yield ((x + 1, y), puzzle_input[y][x + 1])
        if y != height - 1:
            yield ((x, y + 1), puzzle_input[y + 1][x])
        if x != 0:
            yield ((x - 1, y), puzzle_input[y][x - 1])

    heightmap_graph = nx.DiGraph()

    for y, row in enumerate(puzzle_input):
        for x, strength in enumerate(row):
            for neighbour, neighbour_strength in neighbours(x, y):
                if neighbour_strength <= strength + 1:
                    heightmap_graph.add_edge((x, y), neighbour)

    return nx.shortest_path_length(heightmap_graph, start, target)

def main():
    puzzle_input = util.read.as_lines()

    steps = solve(puzzle_input)

    print("The fewest steps required to reach the location with the best signal is " + str(steps) + ".")

class AOC_Tests(unittest.TestCase):
    def test_ex1(self):
        return self.assertEqual(solve(["Sabqponm",
                                       "abcryxxl",
                                       "accszExk",
                                       "acctuvwj",
                                       "abdefghi"]), 31)

if __name__ == "__main__":
    run(main)
Return to solution index