func TestTopologicalSort(t *testing.T) {
	h := graph.NewDirected()
	addEdge := func(h *graph.DirGraph, i, j int) {
		h.AddEdge(graph.VertexId(i), graph.VertexId(j), 1)
	}

	for i := 1; i < 10; i++ {
		h.AddVertex(graph.VertexId(i))
	}

	addEdge(h, 1, 7)
	addEdge(h, 7, 4)
	addEdge(h, 4, 1)

	addEdge(h, 7, 9)

	addEdge(h, 9, 6)
	addEdge(h, 6, 3)
	addEdge(h, 3, 9)

	addEdge(h, 6, 8)

	addEdge(h, 5, 8)
	addEdge(h, 2, 5)
	addEdge(h, 8, 2)

	dfs.DirectedDfs(h, graph.VertexId(9), func(v graph.VertexId) {
		//fmt.Println(v)
	})

	s := Scc(h)
	fmt.Println(s)

}
Example #2
0
func Scc(g *graph.DirGraph) []stack.Stack {
	s := stack.New()
	n := g.Order()
	SCCs := make([]stack.Stack, 0)
	visited := make(map[graph.VertexId]bool)
	vertices := g.VerticesIter()

	for s.Len() != n {
		vertex := <-vertices
		dfs.DirectedDfs(g, vertex, func(v graph.VertexId) {
			if visited[v] == false {
				fmt.Println(vertex, v)
				s.Push(v)
				visited[v] = true
			}
		})
	}

	fmt.Println(s)

	r := g.Reverse()
	visited = make(map[graph.VertexId]bool)
	for s.Len() > 0 {
		vertex := s.Pop().(graph.VertexId)
		scc := stack.New()

		if visited[vertex] == false {
			dfs.DirectedDfs(r, vertex, func(v graph.VertexId) {
				fmt.Println(vertex, v)
				if visited[graph.VertexId(v)] == false {
					visited[graph.VertexId(v)] = true
					fmt.Println(vertex, v)
					scc.Push(v)
				}
			})
		}
		if scc.Len() > 1 {
			SCCs = append(SCCs, *scc)
		}
	}
	return SCCs
}