|
| 1 | +/****************************************************************************** |
| 2 | + * Execution: go run cmd/dijkstra-sp/main.go input.txt s |
| 3 | + * Data files: https://algs4.cs.princeton.edu/44sp/tinyEWD.txt |
| 4 | + * https://algs4.cs.princeton.edu/44sp/mediumEWD.txt |
| 5 | + * https://algs4.cs.princeton.edu/44sp/largeEWD.txt |
| 6 | + * |
| 7 | + * Dijkstra's algorithm. Computes the shortest path tree. |
| 8 | + * Assumes all weights are nonnegative. |
| 9 | + * |
| 10 | + * % go run cmd/dijkstra-sp/main.go tinyEWD.txt 0 |
| 11 | + * 0 to 0 (0.00) |
| 12 | + * 0 to 1 (1.05) 0->4 0.38 4->5 0.35 5->1 0.32 |
| 13 | + * 0 to 2 (0.26) 0->2 0.26 |
| 14 | + * 0 to 3 (0.99) 0->2 0.26 2->7 0.34 7->3 0.39 |
| 15 | + * 0 to 4 (0.38) 0->4 0.38 |
| 16 | + * 0 to 5 (0.73) 0->4 0.38 4->5 0.35 |
| 17 | + * 0 to 6 (1.51) 0->2 0.26 2->7 0.34 7->3 0.39 3->6 0.52 |
| 18 | + * 0 to 7 (0.60) 0->2 0.26 2->7 0.34 |
| 19 | + * |
| 20 | + * % go run cmd/dijkstra-sp/main.go mediumEWD.txt 0 |
| 21 | + * 0 to 0 (0.00) |
| 22 | + * 0 to 1 (0.71) 0->44 0.06 44->93 0.07 ... 107->1 0.07 |
| 23 | + * 0 to 2 (0.65) 0->44 0.06 44->231 0.10 ... 42->2 0.11 |
| 24 | + * 0 to 3 (0.46) 0->97 0.08 97->248 0.09 ... 45->3 0.12 |
| 25 | + * 0 to 4 (0.42) 0->44 0.06 44->93 0.07 ... 77->4 0.11 |
| 26 | + * ... |
| 27 | + * |
| 28 | + ******************************************************************************/ |
| 29 | + |
| 30 | +package main |
| 31 | + |
| 32 | +import ( |
| 33 | + "fmt" |
| 34 | + "os" |
| 35 | + "strconv" |
| 36 | + |
| 37 | + "github.com/shellfly/algo" |
| 38 | + "github.com/shellfly/algo/stdin" |
| 39 | +) |
| 40 | + |
| 41 | +func main() { |
| 42 | + graph := algo.NewEdgeWeightedDigraph(stdin.NewIn(os.Args[1])) |
| 43 | + s, _ := strconv.Atoi(os.Args[2]) |
| 44 | + sp := algo.NewDijkstraSP(graph, s) |
| 45 | + for t := 0; t < graph.V(); t++ { |
| 46 | + if sp.HasPathTo(t) { |
| 47 | + fmt.Printf("%d to %d (%.2f) ", s, t, sp.DistTo(t)) |
| 48 | + for _, e := range sp.PathTo(t) { |
| 49 | + fmt.Print(e, " ") |
| 50 | + } |
| 51 | + fmt.Println() |
| 52 | + } else { |
| 53 | + fmt.Printf("%d to %d no path\n", s, t) |
| 54 | + } |
| 55 | + } |
| 56 | +} |
0 commit comments