-
-
Save RLGGHC/0dd1b7f6ec9ae1cb7649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | |
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 false if @a == -2 | |
add(@a,1) | |
add(@a,-1) | |
add(@a,@w) | |
add(@a,-@w) | |
@a=@s[@a] | |
end | |
return true | |
end | |
def add(p, o) | |
if @s[p+o] == -1 | |
@s[@b] = p+o | |
@b = p+o | |
@g[p+o] = -o | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment