【问题标题】:Routes between two points in a grid网格中两点之间的路线
【发布时间】:2012-05-03 22:05:00
【问题描述】:

给定一个网格点,我试图找到其中两个点之间的路径。

就像这张图片:我需要找到黄线的点:

我可以使用哪些最佳方法/算法?

谢谢

【问题讨论】:

  • 您熟悉广度优先搜索吗?
  • 为什么这条线从 (0,0) 到 (5,4) 而不是 (6,4)?我不明白为什么第一条对角线会出现在它所在的位置,我认为在编写任何代码之前你需要清楚这一点......

标签: algorithm graph graph-algorithm


【解决方案1】:

查看A* algorithm

它在许多视频游戏中用于寻路问题,并且可以构建得非常健壮。

【讨论】:

    【解决方案2】:

    Dijkstra 的算法可以是一个好的开始。

    【讨论】:

      【解决方案3】:

      您还没有完全定义要如何使用对角线,因此您必须根据需要编写最终函数,我想采用使用对角线的路径中长度最短的路径,并注意来自 a> 的路径c 比路径 a>b>c 短于路径中的 a,b,c

      grid = [[False]*16 for i in range(16)]
      #mark grid of walls
      
      def rect(p1,p2):
          x1, y1 = p1
          x2, y2 = p2
          for x in range(x1, x2+1):
              for y in range(y1, y2+1):
                  yield (x, y)
      
      rects = [((1,2),(5,5)),
          ((5,5),(14,15)),
          ((11,5),(11,11)),
          ((5,11),(11,11)),
          ((4,7),(5,13)),
          ((5,13),(13,13))]
      
      for p1,p2 in rects:
          for point in rect(p1,p2):
              x,y = point
              grid[x][y] = True
      
      start = (1,2)
      end = (12,13)
      
      assert(grid[start[0]][start[1]])
      assert(grid[end[0]][end[1]])
      
      def children(parent):
          x,y = parent
          surrounding_points = ((x1,y1) for x1 in range(x-1,x+2) for y1 in range(y-1,y+2) if x1>0 and y<15)
          for x,y in surrounding_points:
              if grid[x][y]:
                  #not a wall
                  grid[x][y] = False
                  #set as wall since we have been there already
                  yield x,y
      
      path = {}
      def bfs(fringe):
          if end in fringe:
              return
      
          new_fringe = []
          for parent in fringe:
              for child in children(parent):
                  path[child] = parent
                  new_fringe.append(child)
          del fringe
          if new_fringe:
              bfs(new_fringe)
      
      bfs([start])
      def unroll_path(node):
          if node != start:
              return unroll_path(path[node]) + [node]
          else:
              return [start]
      
      path = unroll_path(end)
      
      def get_final_path_length(path):
          #return length of path if using straight lines
          for i in range(len(path)):
              for j in range(i+1,len(path)):
                  #if straight line between pathi and pathj
                  return get_final_path(path[j+1:]) + distance_between_i_and_j
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 2010-11-03
        • 2012-12-18
        • 2011-01-02
        • 2011-01-27
        • 2011-10-10
        相关资源
        最近更新 更多