Keeping track of the path, Knights travel

我的未来我决定 提交于 2019-12-11 14:15:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!