|
| 1 | +/* |
| 2 | + Execution: go run cmd/cc/main.go filename.txt |
| 3 | + Data files: https://algs4.cs.princeton.edu/41graph/tinyG.txt |
| 4 | + https://algs4.cs.princeton.edu/41graph/mediumG.txt |
| 5 | + https://algs4.cs.princeton.edu/41graph/largeG.txt |
| 6 | +
|
| 7 | + Compute connected components using depth first search. |
| 8 | + Runs in O(E + V) time. |
| 9 | +
|
| 10 | + % go run cmd/cc/main.go tinyG.txt |
| 11 | + 3 components |
| 12 | + 0 1 2 3 4 5 6 |
| 13 | + 7 8 |
| 14 | + 9 10 11 12 |
| 15 | +
|
| 16 | + % pytyon cc.py mediumG.txt |
| 17 | + 1 components |
| 18 | + 0 1 2 3 4 5 6 7 8 9 10 ... |
| 19 | +
|
| 20 | + % go run cmd/cc/main.go largeG.txt |
| 21 | + 1 components |
| 22 | + 0 1 2 3 4 5 6 7 8 9 10 ... |
| 23 | +
|
| 24 | + Note: This implementation uses a recursive DFS. To avoid needing |
| 25 | + a potentially very large stack size, replace with a non-recurisve |
| 26 | + DFS ala NonrecursiveDFS. |
| 27 | +
|
| 28 | +*/ |
| 29 | + |
| 30 | +package main |
| 31 | + |
| 32 | +import ( |
| 33 | + "fmt" |
| 34 | + "os" |
| 35 | + |
| 36 | + "github.com/shellfly/algo" |
| 37 | + "github.com/shellfly/algo/stdin" |
| 38 | +) |
| 39 | + |
| 40 | +func main() { |
| 41 | + graph := algo.NewGraph(stdin.NewIn(os.Args[1])) |
| 42 | + cc := algo.NewCC(graph) |
| 43 | + |
| 44 | + fmt.Println(cc.Count(), " components") |
| 45 | + var components = []*algo.Bag{} |
| 46 | + for i := 0; i < cc.Count(); i++ { |
| 47 | + components = append(components, algo.NewBag()) |
| 48 | + } |
| 49 | + |
| 50 | + for v := 0; v < graph.V(); v++ { |
| 51 | + components[cc.ID(v)].Add(v) |
| 52 | + } |
| 53 | + |
| 54 | + for i := 0; i < cc.Count(); i++ { |
| 55 | + for _, v := range components[i].Slice() { |
| 56 | + fmt.Print(v, " ") |
| 57 | + } |
| 58 | + fmt.Println() |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments