AdBlock Detected!

Our website is made possible by displaying ads to our visitors. Please support us by whitelisting our website.

Computer Neek

What is graph traversing

A way of visiting different nodes on a graph. There are two types, Depth first(using a stack) and breadth first(using a queue)

Depth first Traversal

image of a graph

First, push A onto the stack and mark it as visited. Then Push B onto the stack and mark it as visited (you choose from either B or D).

image of a stack

Next, you push C to the stack and mark it as visited

image of a stack

You then push E to the stack(you can choose E or D).

image of a stack

Because node E has no neighbours, we remove it from the stack and see if node C has any neighbours that haven't already been visited. Node D has not been visited, so it is pushed to the top of the stack.

image of a stack

D has no neighbours, so it popped. C has no unvisited neighbouring nodes, so it is popped, as are B and A. The stack is now empty, and the search is finished.

Breadth first

image of a graph

Firstly, we enqueue()(add) a node onto the queue. We will choose node A.

image of a queue

Next we visit all of its neighbouring nodes and enqueue it onto the queue.

image of a queue

Since there are no more neighbouring nodes, A is dequeued(remove) the top item from the queue. It's now been visited. Remember its first in first out (FIFO) with queues.

image of a queue

Now you enqueue all the connecting nodes of B which is node C.

Since all of it's child nodes have already been visited, we can dequeue node B. D is also dequeued because there are no connecting nodes.

image of a queue

Finally we enqueue all of node C's neighbours. E is enqueued

image of a queue

Since E has no neighbouring nodes, C is dequeued along with E since it too has no neighbours that haven't already been visited.

image of a queue

Summary

Breadth Traversal(Queue) - You only dequeue if have visited and enqueued all of its neighbouring/child nodes.

Depth Traversal(Stack) - You can pop if you have no more visited child/neighbouring nodes.

To learn about graphs click here or to read about different topics, click here