What is a graph?
- Algorithms course
- Intermediate
- Lesson 49/80
- 4 min
A graph has vertices and edges.
What is a graph?
A graph is a data structure of vertices and edges connecting them. Unlike a tree it can contain cycles.
In a directed graph edges have a direction (A→B); in an undirected one they are bidirectional (A—B). In a weighted graph edges have a cost.
Graphs are used in pathfinding, social networks, dependency resolution.
Directed and undirected
In a directed graph each edge has a direction: A→B means from A to B but not B to A. In an undirected graph A—B can be traversed both ways.
In the adjacency list a directed graph has graph[A] containing only B; an undirected one has both graph[A] and graph[B] containing each other.
Direction is achieved by adding to both sides during insertion.
Practice Create graph
Write create_graph(). Return an empty adjacency dict. Print {} with print(create_graph()).
Starter code
def create_graph():
# Empty graphSample solution
def create_graph():
# Empty graph
return {}
print(create_graph())Expected output
{}
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How does a graph differ from a tree?
- No vertices
- It can contain cycles Correct answer
- No edges
- Has a root
Explanation: It can contain cycles
2 Edge direction
Undirected graph A—B: add B to graph[A] and add A to graph[____]
Undirected graph A—B: add B to graph[A] and add A to graph[A]
Explanation: A is right.
3 What is a graph: match the terms
| Term | Meaning |
|---|---|
Directed |
One way |
Undirected |
Both ways |
Weighted |
Cost |
Cycle |
Allowed |