Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Adam Lum's solution to RPCFN #5 (Mazes)
# Adam Lum's solution to RPCFN #5
# http://rubylearning.com/blog/2009/12/27/rpcfn-mazes-5/
class Maze
attr_accessor :maze_array, :start_point, :end_point
def initialize(in_maze)
@start_point = []
@end_point = []
@maze_array = in_maze.split("\n")
(0..@maze_array.size - 1).each do |i|
@maze_array[i] = @maze_array[i].split(//)
(0..@maze_array[i].size - 1).each do |j|
if (@maze_array[i][j] == "A")
@start_point = [i, j]
end
if (@maze_array[i][j] == "B")
@end_point = [i, j]
end
end
end
end
def try_move(x, y, came_from)
found = false
steps = []
if (@maze_array[x][y] == "B")
return [true, 0]
end
if ((x + 1) < @maze_array.size && came_from != "right")
if (@maze_array[x + 1][y] != "#")
returned_array = try_move(x + 1, y, "left")
if (returned_array[0])
steps << returned_array[1] + 1
end
end
end
if ((x - 1) >= 0 && came_from != "left")
if (@maze_array[x - 1][y] != "#")
returned_array = try_move(x - 1, y, "right")
if (returned_array[0])
steps << returned_array[1] + 1
end
end
end
if ((y + 1) < @maze_array[x].size && came_from != "down")
if (@maze_array[x][y + 1] != "#")
returned_array = try_move(x, y + 1, "up")
if (returned_array[0])
steps << returned_array[1] + 1
end
end
end
if ((y - 1) >= 0 && came_from != "up")
if (@maze_array[x][y - 1] != "#")
returned_array = try_move(x, y - 1, "down")
if (returned_array[0])
steps << returned_array[1] + 1
end
end
end
[steps.size > 0, (steps.size > 0) ? steps.sort.first : 0]
end
def solvable?
try_move(@start_point[0], @start_point[1], "")[0]
end
def steps
try_move(@start_point[0], @start_point[1], "")[1]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment