Sub topic 2
Degree, Paths, and Adjacency Lists
Assume you know lists, dictionaries, sets, queues, stacks, and basic Big-O notation. This chapter uses Python-like examples.
Degree, in-degree, and out-degree
A degree counts the edges connected to a vertex. In an undirected graph, each edge has two directions implicitly, so the degree of B in the graph below is 3.
A directed graph has two degree measures:
- Out-degree: the number of edges leaving a vertex.
- In-degree: the number of edges entering a vertex.
| Graph type | Meaning of degree |
|---|---|
| Undirected | Edges touching the vertex |
| Directed | Usually specify in-degree or out-degree |
| Weighted | Degree counts edges; edge values are separate |
def in_degree(graph, vertex):
return sum(vertex in neighbors for neighbors in graph.values())
def out_degree(graph, vertex):
return len(graph[vertex])
graph = {
"A": {"B": 4},
"B": {},
"C": {"B": 2},
}
print(out_degree(graph, "A")) # 1
print(in_degree(graph, "B")) # 2The weights 4 and 2 do not affect these counts. A weighted degree, sometimes called strength, would add the weights instead.
Paths and cycles
A path is a sequence of vertices connected by edges. In a directed graph, every step must follow the edge direction. A cycle is a path that returns to its starting vertex without repeating intermediate vertices.
Connectivity: components and reachability
In an undirected graph, vertices are connected when a path links them. A connected component is a maximal group of mutually connected vertices.
In a directed graph, reachability depends on direction. Vertex u can reach v if a directed path starts at u and ends at v. This relationship does not have to work in reverse.
Storing a graph as an adjacency list
An adjacency list stores each vertex with its neighboring vertices. A dictionary of dictionaries can also store weights. For an undirected edge, store both directions. For a directed edge, store only the stated direction.
def add_edge(graph, u, v, weight=1, directed=False):
graph.setdefault(u, {})[v] = weight
graph.setdefault(v, {})
if not directed:
graph[v][u] = weight
graph = {}
add_edge(graph, "A", "B", 4)
add_edge(graph, "B", "C", 2)
print(graph)
# {'A': {'B': 4}, 'B': {'A': 4, 'C': 2}, 'C': {'B': 2}}Adjacency lists use space proportional to vertices plus edges, O(V + E). They work well for sparse graphs.
Exercise
In a directed adjacency list, what are the in-degree and out-degree of B in A → B, C → B, and B → D?
Show answer
B has in-degree 2 and out-degree 1.