Skip to content

Commit 2a8ca87

Browse files
committedDec 12, 2022
day 12 part b
1 parent e881e7d commit 2a8ca87

File tree

2 files changed

+28
-4
lines changed

2 files changed

+28
-4
lines changed
 

‎12/a.rb

+2-4
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@
1212
cxy = nodes.select { |k, v| !v[:visited] }.min_by { |k, v| v[:dist] }[0]
1313
cv = grid[*cxy]
1414

15+
p nodes[cxy][:dist] and break if cv == "E"
16+
1517
grid.each_neighbor(*cxy, diags: false) do |nxy, nv|
1618
nodes[nxy] ||= { visited: false, dist: Float::INFINITY }
1719

@@ -21,8 +23,4 @@
2123
end
2224

2325
nodes[cxy][:visited] = true
24-
25-
break if grid[*cxy] == "E"
2626
end
27-
28-
p nodes[grid.index("E")][:dist]

‎12/b.rb

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
require "set"
2+
require_relative "../lib/grid"
3+
4+
grid = Grid.from_file("12/input.txt")
5+
nodes = { grid.index("E") => { visited: false, dist: 0 } }
6+
heights =
7+
{ "S" => 0, "E" => 25 }.tap do |h|
8+
("a".."z").each_with_index { |v, i| h[v] = i }
9+
end
10+
11+
loop do
12+
cxy = nodes.select { |k, v| !v[:visited] }.min_by { |k, v| v[:dist] }[0]
13+
cv = grid[*cxy]
14+
15+
p nodes[cxy][:dist] and break if cv == "a"
16+
17+
grid.each_neighbor(*cxy, diags: false) do |nxy, nv|
18+
nodes[nxy] ||= { visited: false, dist: Float::INFINITY }
19+
20+
if heights[cv] - heights[nv] <= 1
21+
nodes[nxy][:dist] = [nodes[nxy][:dist], nodes[cxy][:dist] + 1].min
22+
end
23+
end
24+
25+
nodes[cxy][:visited] = true
26+
end

0 commit comments

Comments
 (0)
Please sign in to comment.