secret
Created — forked from tardate/paulgallagher.rb

  • Download Gist
paulgallagher.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
class Maze
WALL = '#'
FREE = ' '
def initialize(maze)
@wip_maze = maze.split("\n").collect { |row| row.split('') }
solve
end
def solvable?
steps > 0
end
attr_writer :steps
def steps
@steps ||= calc_steps
end
 
def calc_steps
spaces = @wip_maze.flatten.inject(0) { |s,c| s += (c == FREE) ? 1 : 0 }
spaces > 0 ? spaces + 1 : 0
end
def solve
@wip_maze.each_index do |r|
@wip_maze[r].each_index do |c|
fill_from_deadend?(r,c)
end
end
end
def fill_from_deadend?(r,c)
return false unless @wip_maze[r][c] == FREE
n = (r == 0) || (@wip_maze[r-1][c] == WALL) ? 1 : 0
s = (r == @wip_maze.size-1) || (@wip_maze[r+1][c] == WALL) ? 1 : 0
e = (c == 0) || (@wip_maze[r][c-1] == WALL) ? 1 : 0
w = (c == @wip_maze[r].size-1) || (@wip_maze[r][c+1] == WALL) ? 1 : 0
if (n+s+e+w)>2
@wip_maze[r][c] = WALL
fill_from_deadend?(r-1,c) if n==0
fill_from_deadend?(r+1,c) if s==0
fill_from_deadend?(r,c-1) if e==0
fill_from_deadend?(r,c+1) if w==0
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.