Counting Dead Ends

Let’s show how the frequency of dead ends compare between algorithms. We’ll add a method to our Grid class that will collect all of the dead-end cells in the entire grid—those with links to only one other cell—and return them as a list. Then we can print the size of that list to tell us how many dead ends there are. (We’ll be able to use this later, too, when we start talking about braid mazes in Chapter 9, Braiding and Weaving Your Mazes.)

Open up grid.rb and put this just before the last end keyword in that file.

grid.rb
 
def​ deadends
 
list = []
 
 
each_cell ​do​ |cell|
 
list << cell ​if​ cell.links.count == 1
 
end
 
 
list
 
end

Once you’ve made that change, choose one of your previous programs (for example, ...

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.