class MazeSolver::MazeSolver

Maze solver: solves a maze

Attributes

grid[RW]

Public Class Methods

new(args = {}) click to toggle source
# File lib/maze_solver.rb, line 8
def initialize(args = {})
  @grid = if args[:from_grid]
            args[:from_grid].split("\n")
          elsif args[:from_file]
            from_file(args[:from_file])
          end
  pad_short_rows
end

Public Instance Methods

adjacent_cell_solvable?(start_x, start_y, end_x, end_y) click to toggle source
# File lib/maze_solver.rb, line 64
def adjacent_cell_solvable?(start_x, start_y, end_x, end_y)
  solve(start_x + 1, start_y, end_x, end_y) ||
    solve(start_x, start_y + 1, end_x, end_y) ||
    solve(start_x - 1, start_y, end_x, end_y) ||
    solve(start_x, start_y - 1, end_x, end_y)
end
from_file(filename) click to toggle source
# File lib/maze_solver.rb, line 75
def from_file(filename)
  grid = File.open(filename, 'r').readlines
  grid.each(&:strip!)
end
height() click to toggle source
# File lib/maze_solver.rb, line 22
def height
  grid.size
end
pad_short_rows() click to toggle source
# File lib/maze_solver.rb, line 17
def pad_short_rows
  w = width
  grid.each { |row| row << ' ' * (w - row.length) if w > row.length }
end
solve(start_x, start_y, end_x, end_y) click to toggle source
# File lib/maze_solver.rb, line 50
def solve(start_x, start_y, end_x, end_y)
  return false unless visitable?(start_x, start_y)

  visit(start_x, start_y)

  return true if [start_x, start_y] == [end_x, end_y]

  return true if adjacent_cell_solvable?(start_x, start_y, end_x, end_y)

  unvisit(start_x, start_y)

  false
end
to_s() click to toggle source
# File lib/maze_solver.rb, line 71
def to_s
  grid.join("\n") << "\n"
end
unvisit(x, y) click to toggle source
# File lib/maze_solver.rb, line 44
def unvisit(x, y)
  row = y
  column = x
  grid[row][column] = ' '
end
visit(x, y) click to toggle source
# File lib/maze_solver.rb, line 38
def visit(x, y)
  row = y
  column = x
  grid[row][column] = '.'
end
visitable?(x, y) click to toggle source
# File lib/maze_solver.rb, line 30
def visitable?(x, y)
  row = y
  column = x
  return false unless (0...height).cover? row
  return false unless (0...width).cover? column
  grid[row][column].chr == ' '
end
width() click to toggle source
# File lib/maze_solver.rb, line 26
def width
  grid.map(&:length).max
end