What is a Graph?

Okay, so why should I study graphs?

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

Important Graph Terminology

Nodes

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

Edges

• 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

There are two main ways of traversing a Graph

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.

• 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.
1

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.
1

By Joe Karlsson

Introduction to Graph Traversing

Finding your way around the world of Breadth and Depth First Search

• 609