secret
anonymous / krzysztofkotlarek
Created

  • Download Gist
krzysztofkotlarek
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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
class Maze
attr_reader :steps
def initialize(maze)
#make array
@tab = maze.split('')
 
#find A and B
@start = find_start
@end = find_end
 
@solvable = false
@steps = 0
 
#start queue
@q = []
@q = [@start, 0]
 
#algorithm
work_with_queue
end
 
def solvable?
@solvable
end
 
private
def find_start
@tab.index('A')
end
def find_end
@tab.index('B')
end
 
def find_helper(a)
if @tab[a] == " "
return a
elsif @tab[a] == 'B'
return "finish"
else
return nil
end
end
#find neighbours
def find_top(a)
find_helper(a-38)
end
def find_bottom(a)
find_helper(a+38)
end
def find_left(a)
find_helper(a-1)
end
def find_right(a)
find_helper(a+1)
end
 
#mark neighbours
def mark_neighbour(position,step)
if position and position != "finish"
@tab[position] = step
@q << position << (step + 1)
end
if position == "finish"
@steps = step + 1
@solvable = true
end
end
def find_and_mark_neighbour(position,step)
mark_neighbour(find_top(position),step)
mark_neighbour(find_bottom(position),step)
mark_neighbour(find_left(position),step)
mark_neighbour(find_right(position),step)
end
 
def work_with_queue
while @q.count > 0
position = @q.shift
step = @q.shift
find_and_mark_neighbour(position,step)
end
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.