Graphs and Weighted Graphs
Graphs and Weighted Graphs
A graph is a collection of nodes (vertices) connected by edges. Graphs model relationships: cities connected by roads, web pages connected by links, or maze cells connected by corridors.
Types of Graphs
Unweighted Graph
Every edge has the same cost (implicitly 1). All connections are equal.
Use case: "How many steps to reach the goal?" — BFS answers this optimally.
Weighted Graph
Each edge has a numeric weight representing cost, distance, or time. Some paths are cheaper than others.
Use case: "What's the cheapest route?" — Dijkstra and A* answer this.
Directed vs Undirected
- Undirected: edges go both ways (a road between cities)
- Directed: edges have a direction (a one-way street)
Code Snippet — Graph Representation
The adjacency list is the most common representation for sparse graphs:
class Graph:
"""Unweighted graph using adjacency list."""
def __init__(self, num_nodes: int):
self.num_nodes = num_nodes
self.adjacency_list = [[] for _ in range(num_nodes)]
def add_edge(self, from_node: int, to_node: int):
self.adjacency_list[from_node].append(to_node)
self.adjacency_list[to_node].append(from_node)
def get_neighbors(self, node: int) -> list[int]:
return self.adjacency_list[node]
class WeightedGraph:
"""Weighted graph where each edge has a cost."""
def __init__(self, num_nodes: int):
self.num_nodes = num_nodes
self.adjacency_list = [[] for _ in range(num_nodes)]
def add_edge(self, from_node: int, to_node: int, weight: int):
self.adjacency_list[from_node].append((to_node, weight))
self.adjacency_list[to_node].append((from_node, weight))
def get_neighbors(self, node: int) -> list[tuple[int, int]]:
"""Returns list of (neighbor_node, edge_weight) pairs."""
return self.adjacency_list[node]
Why Weights Matter
On an unweighted graph, the shortest path (fewest edges) is always optimal. BFS finds this.
On a weighted graph, the path with fewest edges might be expensive:
A --1-- B --1-- C (cost: 2, hops: 2)
A --5-- C (cost: 5, hops: 1)
BFS would pick A→C (1 hop) but Dijkstra picks A→B→C (cost 2).
Space Complexity
- Adjacency list: O(V + E) — stores each edge twice for undirected graphs
- Adjacency matrix: O(V^2) — wastes space on sparse graphs but allows O(1) edge lookup
For most pathfinding problems, adjacency lists are preferred because real-world graphs are sparse.
Which Algorithm for Which Graph
| Graph Type | Best Algorithm | Guarantee |
|---|---|---|
| Unweighted | BFS | Shortest path (fewest hops) |
| Weighted (non-negative) | Dijkstra | Cheapest path (minimum total weight) |
| Weighted + goal known | A* | Cheapest path with fewer explorations |
| Weighted (negative edges) | Bellman-Ford | Handles negative weights |
| Unweighted, any path | DFS | Uses less memory than BFS |