Skip to content

Commit b0d1875

Browse files
committedFeb 2, 2020
add cc
1 parent ce2fc6b commit b0d1875

File tree

2 files changed

+107
-0
lines changed

2 files changed

+107
-0
lines changed
 

‎cc.go

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package algo
2+
3+
// CC ...
4+
type CC struct {
5+
marked []bool
6+
id []int
7+
count int
8+
}
9+
10+
// NewCC ...
11+
func NewCC(g *Graph) *CC {
12+
cc := &CC{marked: make([]bool, g.V()), id: make([]int, g.V())}
13+
for s := 0; s < g.V(); s++ {
14+
if !cc.marked[s] {
15+
cc.Dfs(g, s)
16+
cc.count++
17+
}
18+
}
19+
return cc
20+
}
21+
22+
// Dfs ...
23+
func (cc *CC) Dfs(g *Graph, v int) {
24+
cc.marked[v] = true
25+
cc.id[v] = cc.count
26+
for _, w := range g.Adj(v) {
27+
if !cc.marked[w] {
28+
cc.Dfs(g, w)
29+
}
30+
}
31+
}
32+
33+
// Connected ...
34+
func (cc *CC) Connected(v, w int) bool {
35+
return cc.id[v] == cc.id[w]
36+
}
37+
38+
// ID ...
39+
func (cc *CC) ID(v int) int {
40+
return cc.id[v]
41+
}
42+
43+
// Count ...
44+
func (cc *CC) Count() int {
45+
return cc.count
46+
}

‎cmd/cc/main.go

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)
Please sign in to comment.