问题
So far my shortest path method will stop when it reaches the goal position, printing out everything it did along the way. I would like to know how I could go about implementing parent positions so I can print the path along with the goal. This is an assignment.
class Knight
attr_accessor :x, :y, :prev_position, :moves
def initialize(position)
@x = position[0]
@y = position[1]
@prev_position = nil
@moves = [
[-1,-2],
[-2,-1],
[-2,+1],
[-1,+2],
[+1,-2],
[+2,-1],
[+2,+1],
[+1,+2]]
end
def possible
move_list = Array.new
@moves.each do |moves|
x = @x + moves[0]
y = @y + moves[1]
if x.between?(0,7)
if y.between?(0,7)
move_list << [x,y]
end
end
end
move_list
end
end
def shortest_path(position,goal)
paths = Array.new
@start_knight = Knight.new(position)
until @start_knight.x == goal[0] and
@start_knight.y == goal[1]
@start_knight.possible.each do |p| paths << p end
shifted = paths.shift
@start_knight.x = shifted[0]
@start_knight.y = shifted[1]
puts "[#{@start_knight.x},#{@start_knight.y}]"
end
end
shortest_path([0,0],[7,7])
来源:https://stackoverflow.com/questions/46187888/keeping-track-of-the-path-knights-travel