DSA Graphs — Fundamentals Visualized
Learn graph fundamentals — vertices, edges, directed vs undirected, weighted graphs, interactive visualizer, and real-world network examples.
Introduction
Graphs model relationships — unlike trees (one parent per node), graphs allow arbitrary connections, cycles, and multiple paths between vertices.
Social networks, road maps, dependency graphs, and the web are all graphs.
Quick index
| # | Section |
|---|---|
| 1 | How graphs work |
| 2 | Interactive visualizer |
| 3 | Full implementation |
| 4 | Graph types |
| 5 | vs trees |
| 6 | Real-life examples |
1. How graphs work
A
/ \
B C
/ \ \
D E FA graph G = (V, E) has a set of vertices V and edges E connecting them.
| Term | Meaning |
|---|---|
| Vertex (node) | An entity — user, city, web page |
| Edge (link) | A connection between two vertices |
| Degree | Number of edges touching a vertex |
| Path | Sequence of edges connecting two vertices |
| Cycle | Path that starts and ends at the same vertex |
2. Interactive visualizer
Graphs — Fundamentals
Vertices and edges model networks — social graphs, maps, dependencies, and the web.
A graph G = (V, E) — vertices (nodes) connected by edges (links).
Graph basics
// V = { A, B, C, D, E, F }
// E = { A-B, A-C, B-D, B-E, C-F }
const graph = {
A: ["B", "C"],
B: ["A", "D", "E"],
C: ["A", "F"],
// ...
}Unlike trees, graphs can have cycles and multiple paths between nodes.
Vertices
6
Edges
5
Space
O(V+E)
3. Full implementation
class Graph {
constructor(directed = false) {
this.adj = new Map()
this.directed = directed
}
addVertex(v) {
if (!this.adj.has(v)) this.adj.set(v, [])
}
addEdge(a, b, weight = 1) {
this.addVertex(a)
this.addVertex(b)
this.adj.get(a).push({ to: b, weight })
if (!this.directed) this.adj.get(b).push({ to: a, weight })
}
getNeighbors(v) {
return this.adj.get(v) ?? []
}
hasEdge(a, b) {
return this.getNeighbors(a).some((e) => e.to === b)
}
degree(v) {
return this.getNeighbors(v).length
}
vertexCount() {
return this.adj.size
}
}
function buildSampleGraph() {
const g = new Graph(false)
;['A', 'B', 'C', 'D', 'E', 'F'].forEach((v) => g.addVertex(v))
g.addEdge('A', 'B')
g.addEdge('A', 'C')
g.addEdge('B', 'D')
g.addEdge('B', 'E')
g.addEdge('C', 'F')
return g
}Function calls with output
// ── Demo calls — output shown on the right ──
const g = buildSampleGraph()
g.vertexCount() // → 6
g.getNeighbors('A') // → [{ to:'B', weight:1 }, { to:'C', weight:1 }]
g.degree('B') // → 3
g.hasEdge('A', 'C') // → true
g.hasEdge('D', 'F') // → false4. Graph types
| Type | Edges | Example |
|---|---|---|
| Undirected | Two-way | Facebook friends |
| Directed | One-way | Twitter follows |
| Weighted | Cost on edge | GPS distance |
| Unweighted | All equal | Web page links |
| Cyclic | Has a cycle | Circular dependency |
| Acyclic (DAG) | No cycles | Build pipeline |
5. vs trees
| Structure | Connections | Cycles | Root |
|---|---|---|---|
| Tree | Parent → children | No | Yes (single) |
| Graph | Any vertex to any | Yes | No |
6. Real-life examples
| Scenario | Graph role |
|---|---|
| Social network | Users = vertices, friendships = edges |
| Google Maps | Intersections = vertices, roads = weighted edges |
| npm dependencies | Packages = vertices, requires = directed edges |
| Web crawling | Pages = vertices, hyperlinks = directed edges |
Social network friend graph
Users are vertices, friendships are edges — mutual connections form an undirected graph.
Each user becomes a vertex in the graph.
Real-world implementation
class SocialGraph {
constructor() { this.adj = new Map() }
addUser(id) { if (!this.adj.has(id)) this.adj.set(id, new Set()) }
addFriendship(a, b) {
this.addUser(a); this.addUser(b)
this.adj.get(a).add(b)
this.adj.get(b).add(a)
}
friendsOf(id) { return [...(this.adj.get(id) ?? [])] }
mutualFriends(a, b) {
const fa = this.adj.get(a) ?? new Set()
return [...(this.adj.get(b) ?? [])].filter(f => fa.has(f))
}
}Full working code for the scenario above.
Function calls with output
| // ── Function calls with output ── | |
| const net = new SocialGraph() | |
| net.addUser("Alice"); net.addUser("Bob") | → 2 vertices |
Side output shows return value after each call — step through to trace execution.
Summary
Graphs model arbitrary relationships — vertices and edges with optional direction and weight. Next: how to store them efficiently.
Next reads: Graphs Implementation · Graph Traversal
Subscribe to my newsletter
Stay up to date and get notified when I share new contents.
No spam ever, unsubscribe anytime