progress. tech. cats. coffee. art. food. photog. mpls.
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
- Navigation (Shortest path)
- 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
is the process of visiting (checking and/or updating) each vertex in a graph.
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.
- 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.
Rules to follow: Push first vertex A on to the Stack
- If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
- If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
- If you can’t follow Rule 1 or Rule 2, you’re done.
Rules to follow: Make starting Vertex A the current vertex
- Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
- 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.
- If you can’t carry out Rule 2 because the queue is empty, you’re done.
Introduction to Graph Traversing
By Joe Karlsson