What is a Graph?
Lesson 2 of 14 in Coddy's Graphs - Data Structures Series #9 course.
A graph is a data structure that models a set of things and the connections between them. The things are called vertices (or nodes) and the connections are called edges.
Graphs are everywhere. Social networks are graphs (people are vertices, friendships are edges). Road maps are graphs (intersections are vertices, streets are edges). The internet, dependency trees, and game maps are all graphs.
In this course we focus on an undirected graph: if an edge connects u and v, then v is also connected to u. There is no direction. We will use integers as the vertex keys to keep things simple.
Internally we will store the graph as an adjacency list: a map from each vertex to the list of its neighbors. This makes looking up a vertex's neighbors a single map access, which is what most graph algorithms need.
The operations we will build on our Graph class are:
- addVertex: Add a new vertex with no edges yet.
- addEdge: Connect two vertices.
- hasEdge: Check whether two vertices are connected.
- getNeighbors: Get the list of a vertex's neighbors.
- removeEdge: Disconnect two vertices.
- size: Count how many vertices the graph has.
Let's build a Graph class!
Try it yourself
This lesson doesn't include a code challenge.