The Language of Graphs: Vertices and Edges
A graph G = (V, E) models arbitrary relationships without fixed hierarchy. V are vertices; E are edges or connections.
Adjacency Matrix vs Adjacency List
Representation depends on density. Dense graphs (|E| ≈ |V|²) fit matrices; sparse graphs (|E| ≪ |V|²) save memory with lists.
| A (0) | B (1) | C (2) | D (3) |
|---|
Space: O(V²). Adjacency lookup: O(1).
Space: O(V + E). Adjacency lookup: O(degree(v)).
BFS (Breadth-First Search): The Expanding Wave
BFS expands layer by layer from root using a FIFO Queue. Finds the shortest path in number of hops.
DFS (Depth-First Search): Ariadne’s Thread
DFS plunges deep into one path until reaching a dead end and then backtracks. Uses a LIFO Stack or the recursion call stack.
Starting at root node A
Dijkstra’s Algorithm: Relaxation with PriorityQueue
Computes single-source shortest paths on non-negative weighted graphs. Greedy paradigm with edge relaxation.
| Vertex | Tentative Dist | Previous | Settled |
|---|
Source node A starts with dist 0. All others at infinity (∞).
Floyd-Warshall Algorithm: All-Pairs Shortest Paths
Computes all-pairs shortest paths in O(V³). Gradually checks if routing through pivot k yields a shorter path between i and j.
D[i][j] = Math.min(D[i][j], D[i][k] + D[k][j]) | D^(k) | A | B | C |
|---|