func ShortestPath(g *graph.DirGraph, start graph.VertexId) (dist map[graph.VertexId]int) {
	dist = make(map[graph.VertexId]int)
	visited := make(map[graph.VertexId]bool)

	getDist := func(v graph.VertexId) {
		neighbours := g.GetNeighbours(v).VerticesIter()
		visited[v] = true

		for neighbour := range neighbours {

			ok, _ := visited[neighbour]
			if !ok {
				dist[neighbour] = dist[v] + 1
			}
		}
	}

	bfs.Bfs(g, start, getDist)

	return
}
示例#2
0
func Bfs(g *graph.DirGraph, start graph.VertexId, fn func(graph.VertexId)) {
	queue := []graph.VertexId{start}
	visited := make(map[graph.VertexId]bool)
	var next []graph.VertexId

	for len(queue) > 0 {
		next = []graph.VertexId{}
		for _, vertex := range queue {
			visited[vertex] = true
			neighbours := g.GetNeighbours(vertex).VerticesIter()
			fn(vertex)

			for neighbour := range neighbours {

				_, ok := visited[neighbour]
				if !ok {
					next = append(next, neighbour)
				}
			}
		}
		queue = next
	}
}