Finding your way around the world of Graph Traversal

What is a Graph?

A graph consists of some points and some lines between them

A graph with three vertices and three edges.

Okay, so why should I study graphs?

  • Lots of things IRL make sense to be represented as graphs
    • Networks
    • Navigation (Shortest path) 
    • Search
    • Artificial Intelligence (Game AI)
    • Web crawling
  • Also, it's a common interview question

Important Graph Terminology


  • Also known as vertices, or points
  • A graph consists of two or more nodes
  • Pretty simple ...


  • Also known as arcs, or lines
  • Edges connect nodes together on a graph
  • Graphs may also associate to each edge value, such as  cost, capacity, length, etc.
  • Edges can be directed or undirected

Graph Traversal

is the process of visiting (checking and/or updating) each vertex in a graph.

There are two main ways of traversing a Graph

  • Depth-first

  • Breath-first

So what's the difference?

This picture should give you the idea about the context in which the words breadth and depth are used.

  • Depth-first search
    •  Acts as if it wants to get as far away from the starting point as quickly as possible.


  • Breadth-first search
    • Likes to stay as close as possible to the starting point.

Depth-first Search


Rules to follow: Push first vertex A on to the Stack

  1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
  2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
  3. If you can’t follow Rule 1 or Rule 2, you’re done.

Breadth-first Search


Rules to follow: Make starting Vertex A the current vertex

  1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
  2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
  3. If you can’t carry out Rule 2 because the queue is empty, you’re done.