Through the maze: breadth-first search
Chunky is standing at the entrance of a maze, and somewhere inside lies a strip of bacon π₯. Which way is the shortest? You could wander about and hope β or let Ruby search, so cleverly that the first way it finds is guaranteed to be the shortest. For that the maze becomes data: an array of strings, one string per row. # is a wall, . a path, S the start and G the goal, the bacon. maze[row][col] reads one square β the row first, then the column, both counted from 0:
maze = [
"##########",
"#S...#...#",
"#.##.#.#.#",
"#.#..#.#.#",
"#.#.##.#.#",
"#...#..#G#",
"###...##.#",
"#...#....#",
"##########"
]
puts maze
maze[1][1]Where exactly is the S? Every row is a string, and index tells you at which position a character first turns up β or nil if it isn't there at all. So walk through the rows with each_with_index; the first row with an index is the one. The method returns the place as a pair [row, col], and from now on such a pair is called a cell:
def locate(maze, char)
maze.each_with_index do |line, row|
col = line.index(char)
return [row, col] if col
end
nil
end
p locate(maze, "S")
locate(maze, "G")From a cell Chunky can step up, down, left or right β no diagonals, no climbing over walls. A neighbour counts only if it lies inside the maze and is not a wall. The βinsideβ needs care in Ruby: maze[-1] is no error but the last row, and a column past the end of a string gives nil β which is no wall either. So test the numbers first, and only then look at the square. A cell with three ways out:
def open_neighbours(maze, cell)
row, col = cell
moves = [[row - 1, col], [row + 1, col], [row, col - 1], [row, col + 1]]
moves.select do |r, c|
inside = r >= 0 && c >= 0 && r < maze.length && c < maze[r].length
inside && maze[r][c] != "#"
end
end
p open_neighbours(maze, [1, 1])
open_neighbours(maze, [5, 3])Now the search. Imagine dropping a stone into a pond at S: the ripples spread ring by ring. First every cell one step away, then every cell two steps away, and so on β that is breadth-first search. To go ring by ring, Ruby keeps the cells still to be visited in a queue, like the one at the breakfast buffet: push adds at the back, shift takes from the front. Whoever came first is served first:
queue = ["Chunky", "Kaz"]
queue.push("Isi") # Isi joins at the back
p queue.shift # the first in line is served first
p queue.shift
queueThe search needs just that queue and a hash dist: for every cell found so far, how many steps it lies from S. At the start that is only S itself, with 0. Then, over and over: take the front cell out of the queue; every neighbour that is not in dist yet gets one step more than this cell and joins the back of the queue. The dist.key?(n) test makes sure every cell is visited only once β otherwise Chunky would run in circles. Press β― and watch the queue grow and shrink:
start = locate(maze, "S")
dist = { start => 0 }
queue = [start]
until queue.empty?
cell = queue.shift
open_neighbours(maze, cell).each do |n|
next if dist.key?(n)
dist[n] = dist[cell] + 1
queue.push(n)
end
end
dist[locate(maze, "G")]15 steps. Why is that the shortest way? The queue serves the cells in the order they were found: all cells of ring 1 before any of ring 2, all of ring 2 before ring 3. So when the wave first reaches the bacon, there can be no shorter way β it would have arrived in an earlier ring. Draw the rings into the maze and you can see the waves. Each digit is the number of steps, or rather its last digit: after 9 comes 0 again:
maze.each_with_index do |line, r|
rings = line.length.times.map do |c|
d = dist[[r, c]]
line[c] == "." && d ? (d % 10).to_s : line[c]
end
puts rings.join
end
dist.sizeTwo waves run round the walls and meet in the top right corner; the bacon is reached first from below, after 15 steps. And dist.size counts every cell the waves reached: 37, all squares that aren't walls β the paint bucket of a drawing program fills an area just like that. And the way itself? The rings show it, backwards: the bacon lies in ring 15, one of its neighbours in ring 14, one of its neighbours in ring 13 β¦ down to 0, the start. So from the goal, always step to a neighbour one ring closer β find picks the first one β and turn the list round at the end:
cell = locate(maze, "G")
path = [cell]
while dist[cell] > 0
ring = dist[cell] - 1
cell = open_neighbours(maze, cell).find { |n| dist[n] == ring }
path << cell
end
path.reverseThat is Chunky's way: 16 cells from S to G, 15 steps. (Many programs keep a second hash for it instead, came_from[n] = cell β a trail of crumbs from every cell back to the one it was found from. Here the rings do the same job.) Now draw it in. Careful with the copy: maze.dup would copy only the array, and the strings in it would be the very same ones β you saw it with the arrows in lesson 8. And picture[r][c] = "*" changes a string in place: it swaps the character at position c. map(&:dup) copies every single row:
picture = maze.map(&:dup)
path.each do |r, c|
picture[r][c] = "*" if picture[r][c] == "."
end
puts pictureThe maze itself is still clean β try puts maze. Breadth-first search is worth remembering: a queue for what is still to come, a hash for what has been seen. It finds the shortest way whenever every step costs the same β in mazes, on game boards, through a city's streets, or among friends of friends: how many handshakes lie between you and anybody else? When steps cost different amounts β mud, a hill β a cousin takes over, Dijkstra's algorithm, which always serves the cheapest cell first.
steps_to_bacon(maze): the number of steps on the shortest way from S to G β or nil when walls cut the bacon off. locate and open_neighbours from above help. The check tries several mazes, some of them without an outer wall.# def steps_to_bacon(maze)
# ... # the breadth-first search from S, as above
# ... # the number of steps to G - or nil when there is no way
# end
# p steps_to_bacon(maze)
# p steps_to_bacon(["S.#.G"])
bacon_trail(maze), which returns a new maze with Chunky's shortest way drawn in: every cell between S and G becomes a *, S and G stay as they are, and the maze you were given stays unchanged. When there is no way, it returns nil. (If several ways are equally short, any of them will do.)# def bacon_trail(maze)
# ... # search as in the task, then walk back from G
# ... # a copy of the maze with * on the way - or nil
# end
# puts bacon_trail(maze)