Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

Untitled notebook

2022/day/12/notebook.livemd

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, &amp;match?({_, :start}, &amp;1))
  |> Map.keys()
  |> List.first()

endpoint =
  Map.filter(vertices, &amp;match?({_, :end}, &amp;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(&amp;(not is_nil(&amp;1)))
|> Enum.map(&amp;(length(&amp;1) - 1))
|> Enum.min()