Implementing a Cost-Aware Dikstra’s Algorithm

To make this work in code, we need two things: a cell that can be assigned a weight, and a grid composed of these weighted cells.

The cell is straightforward. We’re just going to subclass Cell and add weight information to it. Also, since our Dijkstra’s algorithm was implemented on Cell, we put our updated implementation in the subclass, too, by overriding the original distances method.

Put the following in weighted_cell.rb.

weighted_cell.rb
Line 1 
require ​'cell'
class​ WeightedCell < Cell
attr_accessor :weight
def​ initialize(row, column)
super​(row, column)
@weight = 1
end
10 
def​ distances
weights = Distances.new(self)
pending = [ self ]
15 
while

Get Mazes for Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.