Structural Foundations

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.

A B C D E
Undirected Graph: Connections are bidirectional. (u, v) is identical to (v, u). Friendship networks or two-way roads.
Memory Structures

Adjacency Matrix vs Adjacency List

Representation depends on density. Dense graphs (|E| ≈ |V|²) fit matrices; sparse graphs (|E| ≪ |V|²) save memory with lists.

4-Node Graph Click edges to toggle
A (0) B (1) C (2) D (3)
A (0) B (1) C (2) D (3)

Space: O(V²). Adjacency lookup: O(1).

Breadth Traversals

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.

Ready to start BFS from node 0 (A)
A (0) B (1) C (2) D (3) E (4) Nivel 0 Nivel 1 Nivel 2
FIFO Queue
[A]
Processing Visited Unvisited
Visit Order
A
Depth Traversals

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.

Ready to explore depth-first
A (0) B (1) C (2) D (3) E (4)
Call Stack / LIFO Stack
dfs(A)
Current Action

Starting at root node A

Weighted Shortest Paths

Dijkstra’s Algorithm: Relaxation with PriorityQueue

Computes single-source shortest paths on non-negative weighted graphs. Greedy paradigm with edge relaxation.

4 2 1 5 8 10 2 3 A B C D E F
PriorityQueue<NodeDist>: (A, 0)
Vertex Tentative Dist Previous Settled

Source node A starts with dist 0. All others at infinity (∞).

Dynamic Programming on Graphs

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.

Relaxation rule with pivot k: D[i][j] = Math.min(D[i][j], D[i][k] + D[k][j])
D^(k) A B C
k = 0: Direct adjacency matrix without intermediate vertices.