跟踪路径,骑士旅行

时间:2017-09-13 02:26:40

标签: ruby graph-algorithm knights-tour

到目前为止,我的最短路径方法将在到达目标位置时停止,打印出它沿途所做的一切。我想知道如何实现父位置,以便我可以打印路径和目标。这是一项任务。

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])

0 个答案:

没有答案