Adjacency list
Also called graph as a dictionary, out-degree.
Each vertex maps to the list of vertices its arrows point to. len(g[v]) is the out-degree, and the edges are the sum of the list lengths: 7 here. An undirected edge appears in both lists.
g = {"A": ["B", "C"],
"B": ["D"],
"C": ["D", "E"],
"D": ["F"], "E": ["F"],
"F": []}
for v in sorted(g):
print(v, len(g[v]))
Careful: Loop over sorted(g), not g, when the order reaches the output: this app's dictionaries don't keep insertion order.
Taught in Graphs in code
Adjacency list or adjacency matrix
Also called graph space, adjacency matrix.
m[i][j] is 1 for an arrow from vertex i to vertex j. With V vertices and E edges, lists are far smaller when each vertex has few neighbors.
| Representation | Space | Is there u → v? |
|---|
| Adjacency lists | | , d neighbors of u |
| Adjacency matrix | | |
Careful: A matrix stores a cell for every pair, joined or not: 1000 vertices take a million cells whatever the number of edges.
Taught in Graphs in code
Breadth-first search (BFS)
Also called BFS, visited set, queue search.
Visits vertices in order of distance from the start. Mark a vertex as seen when it joins the queue, so none is queued twice. with an dequeue such as collections.deque.
def bfs(g, start):
seen = {start}
q = [start]
order = []
while q:
v = q.pop(0)
order.append(v)
for w in g[v]:
if w not in seen:
seen.add(w)
q.append(w)
return order
Careful: Without the seen check, or with q.append(w) outside the if, shared neighbors are visited twice and a cycle never ends.
Taught in Breadth-first search
Fewest edges and the route (BFS)
Also called shortest path, BFS distance, parent links.
The BFS distance dist[w] = dist[v] + 1 is the fewest edges from the start. Walk back through the parents from the goal and reverse to get a fewest-edge route.
def path(g, start, goal):
parent = {start: None}
q = [start]
while q:
v = q.pop(0)
for w in g[v]:
if w not in parent:
parent[w] = v
q.append(w)
if goal not in parent:
return None
route = []
v = goal
while v is not None:
route.append(v)
v = parent[v]
return route[::-1]
Careful: BFS counts edges and ignores weights; for least total weight use Dijkstra.
Taught in Fewest edges
Depth-first search (DFS)
Also called DFS, recursive graph search.
Goes as deep as it can along the first unseen neighbor, then backs up. Called as dfs(g, "A", []). .
def dfs(g, v, seen):
seen.append(v)
for w in g[v]:
if w not in seen:
dfs(g, w, seen)
return seen
Careful: A version with an explicit stack pops the last neighbor pushed, so it visits in a different order. Without the seen test a cycle recurses until RecursionError.
Taught in Depth-first search
Topological order (DFS)
Also called topological sort, DAG, directed acyclic graph.
Every arrow points forward in the result. A vertex finishes after everything it points to, so finishing order reversed works. A DAG often has many valid orders. .
def visit(g, v, seen, done):
seen.append(v)
for w in g[v]:
if w not in seen:
visit(g, w, seen, done)
done.append(v)
def topo(g):
seen = []
done = []
for v in sorted(g):
if v not in seen:
visit(g, v, seen, done)
return done[::-1]
Careful: With a cycle no topological order exists; this version doesn't notice and returns a list that breaks an arrow.
Taught in Topological order
Dijkstra's algorithm
Also called weighted shortest path, relax an edge, least-weight path.
Lists hold (neighbor, weight) pairs; INF = float("inf"). Pop the nearest entry and relax its edges. Out-of-date entries pop later and change nothing. with a binary heap.
def dijkstra(g, start):
dist = {v: INF for v in g}
dist[start] = 0
pq = [(0, start)]
while pq:
d, v = heappop(pq)
for w, wt in g[v]:
nd = d + wt
if nd < dist[w]:
dist[w] = nd
heappush(pq, (nd, w))
return dist
Careful: Needs every weight to be zero or more: a negative edge can undercut a vertex already fixed.
Taught in Dijkstra's algorithm
Choosing a graph algorithm
Also called BFS or Dijkstra, which graph search.
Ask what the answer counts and what the edges carry.
| The problem asks for | Algorithm | Cost |
|---|
| Fewest edges | BFS | |
| Least total weight, none negative | Dijkstra | |
| An order keeping every arrow forward | Topological order | |
| Any route, or everything reachable | BFS or DFS | |
Careful: With every weight equal, fewest edges is also least weight, and BFS is enough.
Taught in Which algorithm?
Spanning tree
Also called BFS tree, DFS tree, minimum spanning tree.
A spanning tree joins every vertex of a connected graph with no cycle, using V − 1 edges. The parent links of a search form one; the BFS tree keeps every vertex at its distance from the start. The minimum spanning tree has the least total weight (Prim's or Kruskal's algorithm).
Careful: A minimum spanning tree is not Dijkstra's shortest-path tree: one minimizes the total weight, the other each vertex's distance from the start.
Taught in Trees inside graphs