Sub topic 1
What a Graph Is: Vertices and Edges
Prerequisites
This chapter assumes basic programming with lists, dictionaries, functions, and sets. You should also know simple Big-O notation and understand queues and stacks.
What a Graph Is: Vertices and Edges
A graph models relationships. It contains:
- A vertex, also called a node, which represents an object.
- An edge, which represents a relationship between two vertices.
For example, a social network can model people as vertices and friendships as edges. A map can model locations as vertices and roads as edges.
The meaning of an edge depends on the graph type.
Undirected Graphs: Symmetric Relationships
An undirected graph has edges with no direction. If an edge connects A and B, you can travel from A to B and from B to A.
This models symmetric relationships such as:
- A friendship
- A two-way road
- A shared project
In an undirected graph, the edge {A, B} is the same as {B, A}. A common mistake is to store only one direction when the relationship should work both ways.
Directed Graphs: One-Way Relationships
A directed graph, or digraph, gives each edge a direction. The edge A → B means that the relationship goes from A to B. It does not automatically imply B → A.
Directed graphs model:
- Web pages and hyperlinks
- Prerequisite relationships
- One-way streets
- Followers in a social network
A directed graph can contain both A → B and B → A, but those are separate edges.
Weighted Graphs: Edges That Carry a Value
A weighted graph assigns a value to each edge. The value might represent distance, cost, time, or capacity.
For example, an edge from A to B with weight 4 could mean that the road is four kilometers long. Weights can be attached to undirected or directed edges.
| Graph type | Edge meaning | Example |
|---|---|---|
| Undirected | A symmetric connection | Friendship |
| Directed | A one-way connection | Hyperlink |
| Weighted | A connection with a value | Road length |
Exercise
A delivery route allows travel from warehouse A to warehouse B, but not back. Each route also has a travel time. What graph model fits?
Show answer
A directed, weighted graph. The direction represents the allowed travel, and the weight represents travel time.