【问题标题】:Netlogo Dijkstra algorithmNetlogo Dijkstra 算法
【发布时间】:2021-03-13 07:49:15
【问题描述】:
to-report find-path [ init final ]
  ask init [set dist_d 0]
  let current init
  let p_dij []
  set p_dij insert-item 0 p_dij current 
  show "dij"
  while [not (current = final)] 
  [
    ask [neighbors with [pcolor = yellow and not (dist_d = -1)]] of current [set dist_d min (list dist_d (1 + [dist_d] of current))]
    ask current [set dist_d -1]
    let min_d min [dist_d] of neighbors
    set current one-of neighbors with [dist_d = min_d and pcolor = yellow]
    set p_dij insert-item (length p_dij - 1) p_dij current 
  ]
  ask patches with [pcolor = yellow] [set plabel dist_d set plabel-color red]
  report p_dij
end

我正在尝试使用 Dijkstra 算法找到最短路径。邻居有问题,每次程序试图找到下一个当前节点时,都会回到init。

【问题讨论】:

    标签: netlogo dijkstra


    【解决方案1】:

    这不是您问题的直接答案,如果您想弄清楚如何将 Dijkstra 的算法编码为自己的练习,这对您没有帮助,但如果您只是在寻找最短路径,您可以随时使用网络扩展中的nw:path-to。

    该原语实际上在后台使用了 Dijkstra 算法。

    但是,为了使用它,您需要一个实际的网络,因此您必须使用海龟而不是补丁。然而,这很容易做到。假设您有一个名为 nodes 的海龟品种,您可以通过以下方式在每个补丁上放置一个节点:

    ask patches [
      sprout-nodes 1 [
        set color pcolor ; give the node the same color as the patch
        set hidden? true ; hide the node if you prefer not seeing it
      ]
    ]
    

    然后您可以在黄色节点之间创建链接:

    ask nodes with [ color = yellow ] [
      create-links-with (nodes-on neighbors) with [ color = yellow ]
    ]
    

    从一个黄色节点到另一个黄色节点的路径就是:

    let yellow-nodes nodes with [ color = yellow ]
    show [ nw:path-to one-of other yellow-nodes ] of one-of yellow-nodes
    

    如果你想要的只是距离,你可以改用nw-distance-to。

    【讨论】:

    • 谢谢!!这正是我想要的!
    猜你喜欢
    • 1970-01-01
    • 2011-06-27
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多