Graphs, traversal, and shortest paths
Section 1 of 4
Graphs go beyond hierarchies. They model the chaos of the real world2from social networks to shipping routes2using two simple primitives: Vertices and Edges.
The 'Noun' of the graph. Represents an entity like a user, a city, or a router.
The 'Verb'. Represents the relationship or connection between two vertices.
Connectivity count. In directed graphs, this splits into In-degree and Out-degree.
"Every Tree is a Graph, but not every Graph is a Tree."
Undirected: Edges are mutual. Relationship exists in both directions simultaneously.
How do we store this mess in a computer? We have two competing standards: one for Fast Access and one for Space Efficiency.
Select Matrix or List to see how this specific network structure maps to memory.
| Operation | Adjacency List | Adjacency Matrix |
|---|---|---|
| Space Complexity | O(V + E) | O(V2) |
| Checking Edge (u,v) | O(Degree) | O(1) |
| Finding Neighbors | O(Degree) | O(V) |
| Memory Profile | Ptr Chasing (Cache Misses) | Contiguous (Cache Friendly) |
When asked to store a graph with billions of nodes (like Facebook's social graph), always choose an Adjacency List. Why? Facebook is a **Sparse Graph**. Most people don't have billions of friends; the matrix would be 99.9999% zeros2a catastrophic waste of memory.
The blueprint for a production-ready Graph class using an Adjacency List.
1// Optimal Adjacency List (using a Hash Map)2class Graph {3 constructor() {4 this.adjList = new Map();5 }6 7 addVertex(v) {8 if (!this.adjList.has(v)) {9 this.adjList.set(v, []);10 }11 }12 13 addEdge(v, w, isDirected = false) {14 this.addVertex(v);15 this.addVertex(w);16 this.adjList.get(v).push(w);17 if (!isDirected) {18 this.adjList.get(w).push(v);19 }20 }21 22 getNeighbors(v) {23 return this.adjList.get(v) || [];24 }25}Now that we can store graphs, let's learn how to walk through them with BFS/DFS.