From 3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 Mon Sep 17 00:00:00 2001 From: Alex Pickering Date: Fri, 7 Feb 2025 12:49:48 -0600 Subject: inital commit --- 12/2.lua | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 12/2.lua (limited to '12/2.lua') diff --git a/12/2.lua b/12/2.lua new file mode 100644 index 0000000..e4f2c1f --- /dev/null +++ b/12/2.lua @@ -0,0 +1,42 @@ +#!/usr/bin/env lua + +local heights = {} +for i = string.byte('a'),string.byte('z') do + heights[string.char(i)] = i - string.byte('a') +end +heights.S, heights.E = heights.a, heights.z + +local map = {} +local seen, unseen = {},{} +local endpos +for line in io.lines() do + map[#map+1] = {} + for char in line:gmatch("(.)") do + table.insert(map[#map],{height = heights[char], wts = math.huge}) + if char == "S" then + start = {#map,#map[#map]} + map[#map][#map[#map]].wts = 0 + elseif char == "E" then + endpos = {#map,#map[#map]} + elseif char == "a" then + table.insert(unseen, {#map,#map[#map]}) + map[#map][#map[#map]].wts = 0 + end + end +end +local adjacents = {{-1,0},{1,0},{0,-1},{0,1}} +while #unseen > 0 do + local vertex = table.remove(unseen,1) + local data = map[vertex[1]][vertex[2]] + for _, offset in pairs(adjacents) do + local row,col = vertex[1] + offset[1], vertex[2] + offset[2] + if map[row] and map[row][col] and (map[row][col].height <= data.height + 1) then + local adata = map[row][col] + if adata.wts > data.wts + 1 then + adata.wts = data.wts + 1 + table.insert(unseen,{row,col}) + end + end + end +end +print(map[endpos[1]][endpos[2]].wts) -- cgit v1.2.3-70-g09d2