|
| 1 | +/****************************************************************************** |
| 2 | + * Execution: go run cmd/bread-first-paths/main.go G s |
| 3 | + * Dependencies: Graph.java Queue.java Stack.java StdOut.java |
| 4 | + * Data files: https://algs4.cs.princeton.edu/41graph/tinyCG.txt |
| 5 | + * https://algs4.cs.princeton.edu/41graph/tinyG.txt |
| 6 | + * https://algs4.cs.princeton.edu/41graph/mediumG.txt |
| 7 | + * https://algs4.cs.princeton.edu/41graph/largeG.txt |
| 8 | + * |
| 9 | + * Run breadth first search on an undirected graph. |
| 10 | + * Runs in O(E + V) time. |
| 11 | + * |
| 12 | + * % go run cmd/graph/main.go tinyCG.txt |
| 13 | + * 6 8 |
| 14 | + * 0: 2 1 5 |
| 15 | + * 1: 0 2 |
| 16 | + * 2: 0 1 3 4 |
| 17 | + * 3: 5 4 2 |
| 18 | + * 4: 3 2 |
| 19 | + * 5: 3 0 |
| 20 | + * |
| 21 | + * % go run cmd/bread-first-paths/main.go tinyCG.txt 0 |
| 22 | + * 0 to 0 (0): 0 |
| 23 | + * 0 to 1 (1): 0-1 |
| 24 | + * 0 to 2 (1): 0-2 |
| 25 | + * 0 to 3 (2): 0-2-3 |
| 26 | + * 0 to 4 (2): 0-2-4 |
| 27 | + * 0 to 5 (1): 0-5 |
| 28 | + * |
| 29 | + * % go run cmd/bread-first-paths/main.go largeG.txt 0 |
| 30 | + * 0 to 0 (0): 0 |
| 31 | + * 0 to 1 (418): 0-932942-474885-82707-879889-971961-... |
| 32 | + * 0 to 2 (323): 0-460790-53370-594358-780059-287921-... |
| 33 | + * 0 to 3 (168): 0-713461-75230-953125-568284-350405-... |
| 34 | + * 0 to 4 (144): 0-460790-53370-310931-440226-380102-... |
| 35 | + * 0 to 5 (566): 0-932942-474885-82707-879889-971961-... |
| 36 | + * 0 to 6 (349): 0-932942-474885-82707-879889-971961-... |
| 37 | + * |
| 38 | + ******************************************************************************/ |
| 39 | + |
| 40 | +package main |
| 41 | + |
| 42 | +import ( |
| 43 | + "fmt" |
| 44 | + "os" |
| 45 | + "strconv" |
| 46 | + |
| 47 | + "github.com/shellfly/algo" |
| 48 | + "github.com/shellfly/algo/stdin" |
| 49 | +) |
| 50 | + |
| 51 | +func main() { |
| 52 | + graph := algo.NewGraph(stdin.NewIn(os.Args[1])) |
| 53 | + s, _ := strconv.Atoi(os.Args[2]) |
| 54 | + p := algo.NewBreadFirstPaths(graph, s) |
| 55 | + |
| 56 | + for v := 0; v < graph.V(); v++ { |
| 57 | + if p.HasPathTo(v) { |
| 58 | + fmt.Printf("%d to %d: ", s, v) |
| 59 | + for _, x := range p.PathTo(v) { |
| 60 | + if x == s { |
| 61 | + fmt.Print(x) |
| 62 | + } else { |
| 63 | + fmt.Printf("-%d", x) |
| 64 | + } |
| 65 | + } |
| 66 | + fmt.Println() |
| 67 | + } else { |
| 68 | + fmt.Printf("%d and %d: not connected\n", s, v) |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments