Graph Theory Structures
In computer science, graphs are widely used to model social networks (users are nodes, friendships are edges), web links (pages are nodes, hyperlinks are edges), communication networks, and even path planning problems.
GraphIt is like a social network graph:
- Node (Vertex): each person in a social network
- Edge: relationships between people (friendship, following, etc.)
- Weight: the strength of a relationship (closeness, interaction frequency, etc.)
Imagine your city's transportation network: each location (such as home, school, mall) is aPoint, and the roads connecting these places arelines. A graph is the mathematical abstraction of such node-and-line relationships; it is a data structure used to representcomplex relationships between entities.
Real-life examples:
- Map: cities are nodes, roads are edges, distances are weights
- Electrical circuits: components are nodes, wires are edges, resistance is weight
- The Internet: websites are nodes, links are edges, traffic is weight
- Transportation networks: stations are nodes, lines are edges, fares are weights
| Scenario | Other structures | Graph structure |
|---|---|---|
| Social relationships | Hard to express complex relationships | Naturally expresses many-to-many relationships |
| Path planning | Requires complex data structures | Intuitively represents networks and paths |
| Dependency Relationship | Hard to represent cyclic dependencies | Easily handles complex dependencies |
| Network analysis | Cannot express network topology | Perfectly describes network structure |
Basic Graph Terminology
| Term | define | Life Analogy | Representation |
|---|---|---|---|
| Vertex | The basic unit in a graph | A person in a social network | V, u, v |
| Edge | A line connecting two vertices | A relationship between two people | E, (u,v) |
| Degree | The number of edges connected to a vertex | The number of friends a person has | deg(v) |
| Path | A sequence of vertices | A route from A to B | v₁→v₂→…→vₙ |
| Cycle | A path whose start and end are the same | Leaving home and finally returning home | v₁→v₂→…→v₁ |
| Connected graph | There is a path between any two nodes | Everyone can reach each other | |
| Weight | A numeric attribute of an edge | The distance between two cities | w(u,v) |
Classification of Graphs

| Classification criterion | Type | Feature | Application scenarios |
|---|---|---|---|
| Directionality | Undirected graph | Edges have no direction | Friendships, road networks |
| Directed graph | Edges have direction | Following relationships, workflows | |
| Weight | Unweighted graph | All edges have the same weight | Social network relationships |
| Weighted graph | Edges have different weights | Map distances, network traffic | |
| Connectivity | Connected graph | Any two nodes are reachable | Transportation networks |
| Disconnected graph | Isolated nodes exist | Social groups | |
| Cycles | Acyclic graph | No cycles | Task dependencies, family trees |
| Cyclic graph | Contains cycles | Road networks |
Graph Representation Methods
Adjacency Matrix
| Feature | Description | Time Complexity | Space complexity |
|---|---|---|---|
| Storage method | 2D matrix | ||
| Check edge existence | matrix[i][j] != 0 |
O(1) | |
| Add an edge | matrix[i][j] = weight |
O(1) | |
| Delete an edge | matrix[i][j] = 0 |
O(1) | |
| Traverse adjacent vertices | Scan a row/column | O(V) | |
| Space usage | V×V matrix | O(V²) |
Adjacency list
| Feature | Description | Time Complexity | Space complexity |
|---|---|---|---|
| Storage method | Array + linked list | ||
| Check edge existence | Search in the linked list | O(deg(v)) | |
| Add an edge | Add to the linked list | O(1) | |
| Delete an edge | Delete from the linked list | O(deg(v)) | |
| Traverse adjacent vertices | Traverse the linked list | O(deg(v)) | |
| Space usage | Vertex array + edge linked list | O(V+E) |
Basic concepts of graphs
A graph G consists of two sets:
- Vertex set V (Vertex Set): the set of all nodes in the graph.
- Edge set E (Edge Set): the set of lines connecting these nodes. An edge is represented by the two vertices it connects
(u, v).
Example
A simple graph example: representing social network friendships with a dictionary
Vertices: Alice, Bob, Charlie, Diana
Edges: representing the friendships between them
social_graph
=
{
'Alice'
:
[
'Bob'
,
'Charlie'
]
,
Alice is friends with Bob and Charlie
'Bob'
:
[
'Alice'
,
'Charlie'
,
'Diana'
]
,
'Charlie'
:
[
'Alice'
,
'Bob'
]
,
'Diana'
:
[
'Bob'
]
}
(
f
"Vertices (users): {list(social_graph.keys())}"
)
(
f
"Alice's friends (edges): {social_graph['Alice']}"
)
Output:
顶点(用户): ['Alice', 'Bob', 'Charlie', 'Diana']
Alice 的好友(边): ['Bob', 'Charlie']
Graph Classification and Important Concepts
Graphs can be classified into various types based on their edges; understanding these is fundamental to mastering graph theory.
Undirected vs Directed Graphs
| Type | Characteristics of an Edge | Real-life analogy | Example |
|---|---|---|---|
| Undirected graph | An edge has no direction,(A, B) meaning A and B are connected to each other. |
Mutual friendship: if Alice is Bob's friend, then Bob must also be Alice's friend. | Friendships in social networks, connections in circuits. |
| Directed graph | An edge has direction,A -> B meaning a one-way connection from A to B. |
Weibo following: you can follow someone, but they may not follow you. | Web hyperlinks, task dependencies, one-way streets. |

Weighted graphs
In a weighted graph, each edge is assigned a numeric value (weight), which can represent distance, cost, time, or relationship strength.
Example
A weighted graph representing distances between cities (adjacency list form)
weighted_graph
=
{
'Beijing'
:
{
(
'Shanghai'
,
1200
)
,
(
'Tianjin'
,
100
)
}
,
The distance from Beijing to Shanghai is 1200, and to Tianjin is 100
'Shanghai'
:
{
(
'Beijing'
,
1200
)
,
(
'Hangzhou' (a Chinese city name)
,
200
)
}
,
'Tianjin'
:
{
(
'Beijing'
,
100
)
}
,
'Hangzhou' (a Chinese city name)
:
{
(
'Shanghai'
,
200
)
}
}
Key Terms
- Degree: the number of edges connected to a vertex. In a directed graph, it is divided intoin-degree(the number of edges pointing to the vertex) andout-degree(the number of edges pointing out of the vertex).
- Path: a sequence of edges from one vertex to another. For example
A -> B -> C。 - Cycle: a path whose start and end are the same vertex.
- Connected Graph: in an undirected graph, there is a path between any two vertices.
- Strongly Connected Graph: in a directed graph, there is a path between any two verticesBidirectionalpath.
Graph storage methods
How to represent a graph in a computer? There are two main approaches.
Adjacency Matrix
Use a two-dimensional array (matrix)matrix to represent the graph.matrix[i][j] The value of i at vertex j represents the edge situation.
- For an undirected graph, the matrix is symmetric.
- For a weighted graph, matrix values store weights (using special values such as
0or∞to represent no edge). - Advantages: checking whether an edge exists between any two vertices is very fast (
O(1))。 - Disadvantages: it takes up a lot of space (
O(V^2)), wasting space for "sparse graphs" with few edges.
Example
Represent an undirected graph with an adjacency matrix
Vertices: 0-A, 1-B, 2-C
Edges: A-B, A-C
V
=
3
Number of vertices
adj_matrix
=
[
[
0
]
- V
for
_
in
range
(
V
)
]
Add edge A-B (0-1)
adj_matrix
[
0
]
[
1
]
=
1
adj_matrix
[
1
]
[
0
]
=
1
An undirected graph needs the symmetric position set
Add edge A-C (0-2)
adj_matrix
[
0
]
[
2
]
=
1
adj_matrix
[
2
]
[
0
]
=
1
(
"Adjacency matrix:"
)
for
row
in
adj_matrix:
(
row
)
Output:
[0, 1, 1]
[1, 0, 0]
[1, 0, 0]
Adjacency list
Maintain a list (linked list, array, etc.) for each vertex, recording all vertices directly connected to it (and their weights).
- Advantages: space-efficient (
O(V + E)), especially suitable for sparse graphs. It quickly finds all neighbors of a vertex. - Disadvantages: checking whether an edge exists between two vertices is slower (
O(degree(V)))。
Example
Represent the same undirected graph with an adjacency list (dictionary + list)
adj_list
=
{
'A'
:
[
'B'
,
'C'
]
,
A is connected to B and C
'B'
:
[
'A'
]
,
B is connected to A
'C'
:
[
'A'
]
C is connected to A
}
(
"Adjacency list:"
)
for
vertex
,
neighbors
in
adj_list.
items
(
)
:
(
f
"{vertex}: {neighbors}"
)
Graph Traversal Algorithms
Traversal is the foundation of graph algorithms, meaning systematically visiting every vertex in the graph.
There are two main strategies:
Breadth-first search
Breadth-First Search (BFS) is like a "water ripple spreading": starting from the initial node, it visits all direct neighbors first, then the neighbors' neighbors, and so on. It usesQueueto do so.
Algorithm steps:
- Put the starting vertex into a queue and mark it as visited.
- While the queue is not empty: a. Take out the front vertex
v. b. Visitvall unvisited neighbors of it, put them into the queue and mark them as visited. - Repeat step 2.
Example
from
collections
import
deque
def
bfs
(
graph
,
start
)
:
"""Traverse a graph with BFS, returning the visit order"""
visited
=
set
(
[
start
]
)
Record visited vertices
queue
=
deque
(
[
start
]
)
Initialize the queue
result
=
[
]
Store the visit order
while
queue:
vertex
=
queue.
popleft
(
)
result.
append
(
vertex
)
Traverse the current vertex's neighbors
for
neighbor
in
graph
[
vertex
]
:
if
neighbor
not
in
visited:
visited.
add
(
neighbor
)
queue.
append
(
neighbor
)
return
result
Test Data
test_graph
=
{
'A'
:
[
'B'
,
'C'
]
,
'B'
:
[
'A'
,
'D'
,
'E'
]
,
'C'
:
[
'A'
,
'F'
]
,
'D'
:
[
'B'
]
,
'E'
:
[
'B'
,
'F'
]
,
'F'
:
[
'C'
,
'E'
]
}
(
"BFS traversal order (starting from A):"
,
bfs
(
test_graph
,
'A'
)
)
Possible output: ['A', 'B', 'C', 'D', 'E', 'F']
Depth-First Search
Depth-First Search (DFS) is like "walking through a maze": choose a path and follow it to the end, then backtrack and try another path. It usesStack(or recursion) to implement it.
Recursive algorithm steps:
- Starting from vertex
v, mark it as visited. - For
vevery unvisited neighbor of itu: a. recursively callDFS(u)。
Example
def
dfs_recursive
(
graph
,
vertex
,
visited
=
None
,
result
=
None
)
:
"""Implement DFS using recursion"""
if
visited
is
None
:
visited
=
set
(
)
if
result
is
None
:
result
=
[
]
visited.
add
(
vertex
)
result.
append
(
vertex
)
for
neighbor
in
graph
[
vertex
]
:
if
neighbor
not
in
visited:
dfs_recursive
(
graph
,
neighbor
,
visited
,
result
)
return
result
(
"DFS traversal order (starting from A):"
,
dfs_recursive
(
test_graph
,
'A'
)
)
Possible output: ['A', 'B', 'D', 'E', 'F', 'C']
Comparison of Graph Traversal Algorithms:

Classic Applications and Algorithm Overview
Once you master graph representation and traversal, you can explore many classic problems:
-
Shortest Path Problems: in map navigation, find the shortest driving distance between two points.
-
Minimum spanning tree: while keeping all vertices connected, choose the edge set with the minimum total weight (for example, laying the cheapest fiber-optic network for several villages).
-
Topological sort: linearly order the vertices of a directed acyclic graph (DAG) so that for any directed edge
u->v,ucomes beforevin the ordering (for example, arranging the order of courses).