[2016][ruby][13.0] refactor

profile
Alpha Chen 8 years ago
parent 3b5081797f
commit 7f84a1a0a9

@ -12,9 +12,22 @@ class Maze
walls[[x, y]] walls[[x, y]]
end end
def solve(from, to) def solve(start)
seen = Set.new Solver.new(self, start)
current = [[from, 0]] end
class Solver
attr_reader :maze, :seen, :current
def initialize(maze, start)
@maze = maze
@seen = Set.new
@current = [[start, 0]]
end
def walk
return enum_for(__method__) unless block_given?
loop do loop do
pos, count = current.shift pos, count = current.shift
seen << pos seen << pos
@ -25,13 +38,14 @@ class Maze
}.reject {|x,y| }.reject {|x,y|
x.negative? || y.negative? x.negative? || y.negative?
}.reject {|x,y| }.reject {|x,y|
walls[[x,y]] maze[x,y]
}.reject {|x,y| }.reject {|pos|
seen.include?([x,y]) seen.include?(pos)
}.each do |x,y| }.each do |pos|
return count + 1 if to == [x,y] current << [pos, count + 1]
end
current << [[x,y], count + 1] yield [pos, count]
end end
end end
end end
@ -39,7 +53,7 @@ end
if __FILE__ == $0 if __FILE__ == $0
maze = Maze.new(1358) maze = Maze.new(1358)
puts maze.solve([1,1], [31,39]) p maze.solve([1,1]).walk.find {|pos,_| pos == [31,39] }
end end
require 'minitest' require 'minitest'

Loading…
Cancel
Save