secret
Last active

  • Download Gist
amrtamimi.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 48 49 50 51 52 53 54
class Maze
 
def initialize(string)
@data = string
@c = @w = @h = 0
@c = string.length
string.each {|s| @h +=1}
@w = @c / @h
@s = []
@g = []
@number_of_steps = 0 # expect the worst
@a = @b = @goal = @start = 0
end
 
def steps
i = 0
@data.chomp.each do |l|
l.chomp.each_char do |ch|
@s[i] = @g[i] = -1
@s[i] = -2 if ch == '#'
@start = i if ch == 'A'
@goal = i if ch == 'B'
i +=1
end
end
@a = @b = @goal
while @a != @start
return 0 if @a == -2
add(@a,1)
add(@a,-1)
add(@a,@w)
add(@a,-@w)
@a = @s[@a]
end
while @a != @goal
@number_of_steps +=1
@a +=@g[@a]
end
@number_of_steps
end
 
def solvable?
steps > 0
end
 
def add(p, o)
if @s[p+o] == -1
@s[@b] = p+o
@b = p+o
@g[p+o] = -o
end
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.