start multiple paths
This commit is contained in:
parent
45056ce1fa
commit
0f744688b1
1 changed files with 19 additions and 12 deletions
31
21/main.rb
31
21/main.rb
|
@ -74,6 +74,14 @@ def dijkstra_with_lookup(graph, movements, start_char, target_char)
|
|||
dijkstra(graph, movements, start, target)
|
||||
end
|
||||
|
||||
def dijkstra_paths(prev, target, current_path = [])
|
||||
return [current_path.reverse] if prev[target].nil?
|
||||
|
||||
prev[target].flat_map do |parent|
|
||||
dijkstra_paths(prev, parent, current_path + [target])
|
||||
end
|
||||
end
|
||||
|
||||
def dijkstra(graph, movements, start, target)
|
||||
queue = PriorityQueue.new
|
||||
dest = Hash.new
|
||||
|
@ -90,22 +98,20 @@ def dijkstra(graph, movements, start, target)
|
|||
.map { @arrow_dirs[_1] }
|
||||
.map { |dx, dy| [node.first + dx, node.last + dy] }
|
||||
.each do |neighbor|
|
||||
if dest[neighbor].nil? || moves + 1 < dest[neighbor]
|
||||
dest[neighbor] = moves + 1
|
||||
prev[neighbor] = node
|
||||
queue << [neighbor, moves + 1]
|
||||
new_moves = moves + 1
|
||||
if dest[neighbor].nil? || new_moves < dest[neighbor]
|
||||
dest[neighbor] = new_moves
|
||||
prev[neighbor] = [node]
|
||||
queue << [neighbor, new_moves]
|
||||
elsif new_moves == dest[neighbor]
|
||||
prev[neighbor] << node
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
path = Array.new
|
||||
u = target
|
||||
while prev[u]
|
||||
path.unshift(u)
|
||||
u = prev[u]
|
||||
end
|
||||
paths = dijkstra_paths(prev, target)
|
||||
|
||||
return dest, path
|
||||
return dest, paths.first
|
||||
end
|
||||
|
||||
# calculate most efficient number pad paths
|
||||
|
@ -145,6 +151,7 @@ robot_2 = input
|
|||
.map { _1.each_cons(2).to_a }
|
||||
.map { _1.map { |move| number_cache[move].join }.join("A") + "A" }
|
||||
|
||||
debugger
|
||||
|
||||
robot_3 = robot_2
|
||||
.map { _1.chars }
|
||||
|
@ -158,7 +165,7 @@ me = robot_3
|
|||
.map { _1.each_cons(2).to_a }
|
||||
.map { _1.map { |move| arrow_cache[move].join }.join("A") + "A" }
|
||||
|
||||
pp " <vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A"
|
||||
pp "<vA<AA>>^AvAA<^A>A<v<A>>^AvA^A<vA>^A<v<A>^A>AAvA^A<v<A>A>^AAAvA<^A>A"
|
||||
pp me
|
||||
|
||||
me.each_with_index do |entry, i|
|
||||
|
|
Loading…
Reference in a new issue