Data Structures · Visualization
Graph: Introduction
Graph
A graph is a collection of nodes (called vertices) connected by links (called edges). Time: Varies widely by operation and representation (adjacency list vs matrix). Space: O(V + E) with an adjacency list, O(V^2) with an adjacency matrix.
Big-O: BFS/DFS visit each vertex and edge once: O(V + E).
Graph: Introduction
GraphA graph is a collection of nodes (called vertices) connected by links (called edges). Unlike a tree, a graph has no strict hierarchy — any node can connect to any number of other nodes, connections can form cycles, and edges can be one-directional (directed) or two-directional (undirected), and may carry a weight (a cost or distance). Graphs are the most general-purpose structure for modeling relationships and networks.
How Graph: Introduction Works
- Define a set of vertices (nodes), each representing an entity.
- Define a set of edges, each connecting two vertices.
- Decide if edges are directed (one-way) or undirected (two-way).
- Optionally assign weights to edges to represent cost, distance, or capacity.
Graph: Introduction Worked Example
Input: An undirected graph with vertices {A, B, C} and edges A-B, B-C
- Vertices: A, B, C
- Edge A-B means A and B are directly connected
- Edge B-C means B and C are directly connected
- A and C are not directly connected, but reachable through B
Output: A -- B -- C
Press ▶ Run to watch it step by step.
# Adjacency list: vertex -> neighbours
graph = {
"A": ["B", "C"],
"B": ["A", "D"],
"C": ["A", "E"],
"D": ["B"],
"E": ["C"],
}
# Add an edge:
graph["A"].append("D")
# example: introGraph: Introduction Time & Space Complexity
When to Use Graph: Introduction
- Social networks (people as nodes, friendships as edges)
- Road/transportation networks and GPS navigation
- The internet and computer networks
- Recommendation systems and dependency graphs (e.g. build systems)
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Ready for the next step?
See the same ideas in action — visualize the algorithms that operate on these structures, or take a guided course.