项目作者: RyanCarrier

项目描述 :
Fastest golang Dijkstra path finder
高级语言: Go
项目地址: git://github.com/RyanCarrier/dijkstra.git
创建时间: 2017-01-02T02:09:38Z
项目社区:https://github.com/RyanCarrier/dijkstra

开源协议:MIT License

下载


dijkstra

Fast golang Dijkstra’s shortest (and longest) path finder

Documentation

godoc

How to

Install

  1. go get github.com/RyanCarrier/dijkstra/v2

Generate a graph

Importing from file

The package can import dijkstra files in the format:

  1. 0 1,1 2,1
  2. 1 0,1 2,2
  3. 2

using;

  1. data, _ := os.ReadFile("path/to/file")
  2. graph, err := dijkstra.Import(string(data))

i.e. node then each arc and it’s weight. The default is to use nodes with
numbers starting from 0, but the package will map string appropriately (using
ImportStringMapped instead.

Creating a graph

  1. package main
  2. import "github.com/RyanCarrier/dijkstra/v2"
  3. func main(){
  4. graph := dijkstra.NewGraph()
  5. //Add the 3 verticies
  6. graph.AddEmptyVertex(0)
  7. graph.AddEmptyVertex(1)
  8. graph.AddEmptyVertex(2)
  9. //Add the arcs
  10. graph.AddArc(0, 1, 1)
  11. graph.AddArc(0, 2, 1)
  12. graph.AddArc(1, 2, 2)
  13. }

Finding paths

Once the graph is created, shortest or longest paths between two points can be generated.

  1. best, err := graph.Shortest(0, 2)
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println("Shortest distance is", best.Distance, "following path ", best.Path)
  6. best, err = graph.Longest(0, 2)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10. fmt.Println("Longest distance is", best.Distance, "following path ", best.Path)

Finding multiple paths

  1. graph := dijkstra.NewGraph()
  2. //Add the 3 verticies
  3. graph.AddVertexAndArcs(0, map[int]uint64{1: 1, 2: 1})
  4. graph.AddVertexAndArcs(1, map[int]uint64{3: 1})
  5. graph.AddVertexAndArcs(2, map[int]uint64{3: 1})
  6. graph.AddVertexAndArcs(3, map[int]uint64{4: 1})
  7. best, err := graph.ShortestAll(0, 4)
  8. if err != nil {
  9. fmt.Println(graph)
  10. log.Fatal(err)
  11. }
  12. fmt.Println("Shortest distances are", best.Distance, "with paths; ", best.Paths)
  13. best, err = graph.LongestAll(0, 4)
  14. if err != nil {
  15. log.Fatal(err)
  16. }
  17. fmt.Println("Longest distances are", best.Distance, "following path ", best.Paths)