Untitled notebook
Mix.install([{:libgraph, "~> 0.16.0"}])
Section
vertices =
File.read!("input.txt")
|> String.split("\n")
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.flat_map(fn {line, y} ->
line
|> String.split("")
|> Enum.drop(1)
|> Enum.drop(-1)
|> Enum.with_index()
|> Enum.map(fn
{"S", x} -> {{x, y}, :start}
{"E", x} -> {{x, y}, :end}
{<>, x} -> {{x, y}, height}
end)
end)
|> Map.new()
startpoint =
Map.filter(vertices, &match?({_, :start}, &1))
|> Map.keys()
|> List.first()
endpoint =
Map.filter(vertices, &match?({_, :end}, &1))
|> Map.keys()
|> List.first()
vertices =
vertices
|> Map.put(startpoint, hd('a'))
|> Map.put(endpoint, hd('z'))
edges =
vertices
|> Map.to_list()
|> Enum.flat_map(fn {{x, y}, height} ->
[{x - 1, y}, {x + 1, y}, {x, y + 1}, {x, y - 1}]
|> Enum.filter(fn key -> Map.get(vertices, key) <= height + 1 end)
|> Enum.map(fn to -> {{x, y}, to} end)
end)
graph = Graph.new() |> Graph.add_edges(edges)
length(Graph.dijkstra(graph, startpoint, endpoint)) - 1
vertices
|> Map.to_list()
|> Enum.filter(fn {_, height} -> height == hd('a') end)
|> Enum.map(fn {t, _} -> t end)
|> Enum.map(fn s -> Graph.dijkstra(graph, s, endpoint) end)
|> Enum.filter(&(not is_nil(&1)))
|> Enum.map(&(length(&1) - 1))
|> Enum.min()