Пример #1
0
func Sort(g *graph.DirGraph) *stack.Stack {
	var visit func(v graph.VertexId)
	sorted := stack.New()
	visited := make(map[graph.VertexId]bool)
	marked := make(map[graph.VertexId]bool)

	visit = func(v graph.VertexId) {
		if marked[v] {
			panic("Not a Directed Acyclic Graph (DAG)")
		}

		marked[v] = true
		successors := g.GetSuccessors(v).VerticesIter()

		for successor := range successors {
			if !marked[successor] && !visited[successor] {
				visit(successor)
			}
		}

		visited[v] = true
		marked[v] = false
		sorted.Push(v)
	}

	vertices := g.VerticesIter()
	for vertex := range vertices {
		if !visited[vertex] {
			visit(vertex)
		}
	}

	return sorted
}
Пример #2
0
func DirectedDfs(g *graph.DirGraph, v graph.VertexId, fn func(graph.VertexId)) {
	s := stack.New()
	s.Push(v)
	visited := make(map[graph.VertexId]bool)

	for s.Len() > 0 {
		v = s.Pop().(graph.VertexId)

		if _, ok := visited[v]; !ok {
			visited[v] = true
			fn(v)
			neighbours := g.GetSuccessors(v).VerticesIter()
			for neighbour := range neighbours {
				s.Push(neighbour)
			}
		}
	}
}