[2016][ruby][13.0] refactor

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

@ -12,26 +12,40 @@ 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
loop do
pos, count = current.shift class Solver
seen << pos attr_reader :maze, :seen, :current
x,y = pos
def initialize(maze, start)
@maze = maze
@seen = Set.new
@current = [[start, 0]]
end
def walk
return enum_for(__method__) unless block_given?
loop do
pos, count = current.shift
seen << pos
x,y = pos
[[1,0], [-1,0], [0,1], [0,-1]].map {|dx, dy| [[1,0], [-1,0], [0,1], [0,-1]].map {|dx, dy|
[x + dx, y + dy] [x + dx, y + dy]
}.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