Skip to Main Content
Mazes for Programmers
book

Mazes for Programmers

by Jamis Buck
July 2015
Intermediate to advanced content levelIntermediate to advanced
286 pages
6h 31m
English
Pragmatic Bookshelf
Content preview from Mazes for Programmers

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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Exercises for Programmers

Exercises for Programmers

Brian P. Hogan

Publisher Resources

ISBN: 9781680501315Errata Page