{a,b,c,d,e,f}
{(a,c),(a,d),(b,c),(b,f),(c,e),(d,e),(e,f)}
{a,b,c,d,e,f}
{(a,c),(b,c),(b,f),(c,e),(d,a),(d,e)(e,c)(e,f)}
(a,c)
and (a,d)
.BreadthFirst()
method. The breadth first traversal of a graph is like that of a tree, with the exception that graphs can have cycles. Traversing a graph that has cycles will result in an infinite loop….this is bad. To prevent such behavior, we need to have some way to keep track of whether a vertex has been “visited” before. Upon each visit, we’ll add the previously-unvisited vertex to a visited
set, so we know not to visit it again as traversal continues.Enqueue
the declared start node into the Queue.Dequeue
the first node from the queue.Dequeue
‘d node has unvisited child nodes, add the unvisited children to visited
set and insert them into the queue.Look at the code below to take a closer look at what is actually happening. This is the code for a breadth first traversal:
ALGORITHM BreadthFirst(vertex)
DECLARE nodes <-- new List()
DECLARE breadth <-- new Queue()
DECLARE visited <-- new Set()
breadth.Enqueue(vertex)
visited.Add(vertex)
while (breadth is not empty)
DECLARE front <-- breadth.Dequeue()
nodes.Add(front)
for each child in front.Children
if(child is not visited)
visited.Add(child)
breadth.Enqueue(child)
return nodes;
Enqueue
the root.visited
set.Dequeue
the front node and then check to see if it has any children.Push
the root node into the Stack and mark as visited.Pop
the top node off of the stack and check its neighbors.Popping
Nodes off the Stack.Pop
off and be evaluated.Pop
nodes from the top of our stack.Pushed
onto the Stack.Pop
the next node off the Stack: Node H.Pop
off Node F, and again notice that both neighbors Node D and Node H have already been visited, so we don’t add anything to our Stack.