Advent of Code - 2024 Day 10 - Graph
Mix.install([
{:kino_aoc, "~> 0.1.7"},
{:libgraph, "~> 0.16.0"}
])
Section
{:ok, puzzle_input} =
KinoAOC.download_puzzle("2024", "10", System.fetch_env!("LB_AOC_SESSION"))
test_input = """
89010123
78121874
87430965
96549874
45678903
32019012
01329801
10456732
"""
|> String.trim()
grid =
puzzle_input
|> String.split("\n")
|> Enum.map(fn line ->
line
|> :binary.bin_to_list()
|> Enum.map(& &1 - ?0)
end)
grid =
for {row, i} <- Enum.with_index(grid),
{val, j} <- Enum.with_index(row),
into: %{},
do: {{i, j}, val}
graph =
for {coord, _} <- grid, reduce: Graph.new(type: :directed) do
g -> Graph.add_vertex(g, coord)
end
graph =
for {{i1, j1} = coord1, n} <- grid,
coord2 <- [{i1, j1 - 1}, {i1, j1 + 1}, {i1 - 1, j1}, {i1 + 1, j1}],
grid[coord2] == n + 1,
reduce: graph do
g -> Graph.add_edge(g, coord1, coord2)
end
pos0 = grid |> Enum.filter(&elem(&1, 1) == 0) |> Enum.map(&elem(&1, 0))
pos9 = grid |> Enum.filter(&elem(&1, 1) == 9) |> Enum.map(&elem(&1, 0))
Part 1
for start <- pos0,
dest <- pos9,
Graph.get_paths(graph, start, dest) != [],
reduce: 0,
do: (count -> count + 1)
Part 2
for start <- pos0,
dest <- pos9,
paths = Graph.get_paths(graph, start, dest),
reduce: 0,
do: (count -> count + length(paths))