示例#1
0
func (graph *Graph) hasPathBetweenVertices(v1 *Vertex, v2 *Vertex) bool {
	queue := &queue.LinkedQueue{}
	v1.isVisited = true
	for _, edge := range v1.Edges {
		if edge.isUsed {
			queue.Add(edge.ToVertex)
		}
	}
	for queue.Size() > 0 {
		vertex := convertToVertex(queue.Peek())
		if vertex == v2 {
			return true
		} else {
			for _, e := range vertex.Edges {
				if e.isUsed && !e.ToVertex.isVisited {
					queue.Add(e.ToVertex)
				}
			}
		}
		vertex.isVisited = true
		queue.Remove()
	}
	graph.clearVerticesVisitHistory()
	return false
}
func (tree *BinarySearchTree) TraverseByLevel() {
	queue := &queue.LinkedQueue{}
	queue.Add(tree)
	for queue.Size() > 0 {
		t := convertToBinarySearchTree(queue.Peek())
		if t.LeftChild != nil {
			queue.Add(t.LeftChild)
		}
		if t.RightChild != nil {
			queue.Add(t.RightChild)
		}
		fmt.Printf("%d ", t.Value)
		queue.Remove()
	}
}
示例#3
0
func (graph *Graph) BreadthFirstSearch(startVertex *Vertex) {
	if graph.Vertices == nil || len(graph.Vertices) == 0 {
		panic("Graph has no vertex.")
	}
	fmt.Printf("%s ", startVertex.Label)
	startVertex.isVisited = true
	queue := &queue.LinkedQueue{}
	queue.Add(startVertex)
	for queue.Size() > 0 { // Visit the nearest vertices that haven't been visited.
		vertex := convertToVertex(queue.Peek())
		for _, edge := range vertex.Edges {
			if !edge.ToVertex.isVisited {
				fmt.Printf("%s ", edge.ToVertex.Label)
				edge.ToVertex.isVisited = true
				queue.Add(edge.ToVertex)
			}
		}
		queue.Remove()
	}
	graph.clearVerticesVisitHistory()
}