Netlogo Dijkstra algorithm

随声附和 提交于 2021-02-11 14:21:46

问题


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

I'm trying to find the shortest path using Dijkstra's algorithm. There is a problem with the neighbors, every time the program tries to find the next current node, it comes back to init.


回答1:


This is not a direct answer to your question, and won't help you if you're trying to figure out how to code Dijkstra's algorithm as an exercise for yourself, but if you're just looking for a shortest path, you can always use the nw:path-to from the network extension.

That primitive is actually using Dijkstra's algorithm under the hood.

In order to use it, however, you need an actual network, so you would have to use turtles instead of patches. That's easy to do, however. Supposing you have a turtle breed called nodes, you can put a node on each patch by saying:

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

Then you can create links between, say, yellow nodes:

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

The path from one yellow node another is then just:

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

If all you want is the distance, you can use nw-distance-to instead.



来源:https://stackoverflow.com/questions/65089676/netlogo-dijkstra-algorithm

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