计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本:English。

High School Computer Science · 10–12 年级

9Graphs: Networks of Roads and People

A rumour starts in Brenmoor: the library will open on Sundays. Each person who hears it tells their friends the next day. If it starts with the right person, how many days until everyone who can hear it has heard it? And who is the right person?

The question is not about anyone’s personality: it is about the shape of the network of friendships. The same shape appears in the roads between places, the links between web pages and the cables between computers. This chapter names that shape, a graph, stores it in Python, measures distances in it, and finds its centre.

You already know

A dictionary maps keys to values, and a set holds values without order or repetition (Book 1, grade 8, and the chapter on tuples and sets). The Earth and space sciences book explains how a satellite receiver works out its own position on the Earth (grade 9); a map then turns that position into a route.

9.1 Vertices and edges

Definition 9.1 (Graph, vertex, edge)

A graph is a set of vertices together with a set of edges, each edge joining two different vertices. Two vertices joined by an edge are adjacent.

In the friendship graph of Brenmoor the vertices are the people 11 to 4040, and an edge joins two friends. In the road graph the vertices are the 3030 places, and an edge is a road.

Definition 9.2 (Degree, neighbour)

The neighbours of a vertex are the vertices adjacent to it. Its degree is the number of its neighbours.

Definition 9.3 (Directed graph, weighted graph)

In a directed graph each edge goes from one vertex to another, like a one-way street: an edge from aa to bb does not let you go from bb to aa. A vertex then has an out-degree, the number of edges leaving it, and an in-degree, the number of edges arriving. In a weighted graph each edge carries a number, its weight: a length in metres, a time, a price.

The same four vertices and four edges, as an undirected graph, a directed graph and a weighted graph.
The same four vertices and four edges, as an undirected graph, a directed graph and a weighted graph.

9.2 A graph in Python

A graph is stored as a dictionary from each vertex to the set of its neighbours. An undirected edge is written at both of its ends; a vertex without any edge still gets an empty set, so that it is not forgotten.

import csv


def load_friends(path, people=range(1, 41)):
    """Return the friendship graph: a dict person -> set of friends."""
    g = {p: set() for p in people}  # every person is a vertex, even without friends
    with open(path, encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            a, b = int(row["person_a"]), int(row["person_b"])
            g[a].add(b)  # an undirected edge is stored
            g[b].add(a)  # at both of its ends
    return g


if __name__ == "__main__":
    g = load_friends("friendships.csv")
    print(len(g), "vertices")
    print("friends of 1:", sorted(g[1]), " friends of 28:", sorted(g[28]))
    print("without friends:", [p for p in g if not g[p]])
Listing 9.1. The friendship graph as a dictionary of sets. code/grade-10/09-graphs-first-look/listings/load_friends.py
$ python load_friends.py
40 vertices
friends of 1: [5, 7, 10, 12, 28]  friends of 28: [1, 34, 36, 37, 39]
without friends: [40]
Output 9.1. Person 4040 is a vertex with no edge.
from load_friends import load_friends

g = load_friends("friendships.csv")
degree = {p: len(g[p]) for p in g}
count = {}
for d in degree.values():
    count[d] = count.get(d, 0) + 1
for d in sorted(count):
    print(f"degree {d}: {count[d]:2} people  " + "#" * count[d])
print("sum of degrees:", sum(degree.values()))
print("most friends:", [p for p in g if degree[p] == max(degree.values())])
Listing 9.2. How many people have each number of friends. code/grade-10/09-graphs-first-look/listings/degree_table.py
$ python degree_table.py
degree 0:  1 people  #
degree 1: 10 people  ##########
degree 2: 10 people  ##########
degree 3: 10 people  ##########
degree 4:  5 people  #####
degree 5:  4 people  ####
sum of degrees: 100
most friends: [1, 12, 23, 28]
Output 9.2. The degrees add up to 100100, twice the 5050 friendships.

Proposition 9.4 (Sum of the degrees)

In an undirected graph, the sum of the degrees of the vertices is twice the number of edges.

The proof is Exercise 9.12. A road graph needs weights, and one-way roads make it directed: the listing stores a dictionary of neighbours with their distances, and writes a two-way road as two directed edges.

import csv


def load_roads(path):
    """Return the road graph: a dict place -> dict neighbour -> length in metres."""
    g = {}
    with open(path, encoding="utf-8", newline="") as f:
        for row in csv.DictReader(f):
            a, b = int(row["from_place"]), int(row["to_place"])
            g.setdefault(a, {})[b] = int(row["length_m"])
            g.setdefault(b, {})
            if row["one_way"] == "0":  # a two-way road is two directed edges
                g[b][a] = int(row["length_m"])
    return g


if __name__ == "__main__":
    g = load_roads("roads.csv")
    print(len(g), "places,", sum(len(n) for n in g.values()), "directed edges")
    print("from 1 (Town Square):", g[1])
    print("from 3 (Library):    ", g[3])
Listing 9.3. The road graph, directed and weighted. code/grade-10/09-graphs-first-look/listings/load_roads.py
$ python load_roads.py
30 places, 105 directed edges
from 1 (Town Square): {3: 1360, 23: 1210, 24: 1590, 26: 1560}
from 3 (Library):     {24: 1040, 26: 1790}
Output 9.3. 5353 roads give 105105 directed edges: one road, from the Town Square to the Library, is one-way.

A program that builds a graph by hand can forget one end of an edge. The check is short: every edge must have its reverse, except the one-way roads.

from load_friends import load_friends
from load_roads import load_roads


def one_way_edges(g):
    """Return the edges (a, b) of g whose reverse (b, a) is missing."""
    return [(a, b) for a in g for b in g[a] if a not in g[b]]


print("friendships:", one_way_edges(load_friends("friendships.csv")))
print("roads:      ", one_way_edges(load_roads("roads.csv")))
Listing 9.4. Finding the edges without a reverse. code/grade-10/09-graphs-first-look/listings/check_symmetric.py
$ python check_symmetric.py
friendships: []
roads:       [(1, 3)]
Output 9.4. The friendships are symmetric; among the roads, only road 11 is not.

9.3 Paths and distance

Definition 9.5 (Path, length of a path)

A path is a sequence of vertices in which each one is adjacent to the next (in a directed graph, joined by an edge going from it to the next). Its length is its number of edges, or, in a weighted graph, the sum of the weights of its edges.

Definition 9.6 (Distance)

The distance from a vertex aa to a vertex bb is the length of a shortest path from aa to bb. If there is no such path, there is no distance.

Definition 9.7 (Connected graph, component)

An undirected graph is connected if there is a path between any two of its vertices. A connected component is a largest set of vertices joined to one another by paths.

Computing distances in a large graph is an algorithm of its own, written in grade 12. Here two functions are given, in the file given_graphs.py of the grade’s folder, and used without reading them: distances(g, a) returns the dictionary of the distances, in edges, from a to every vertex it can reach, and components(g) returns the components, largest first.

from given_graphs import components
from load_friends import load_friends

g = load_friends("friendships.csv")
for part in components(g):
    people = [str(p) for p in sorted(part)]
    shown = people if len(people) <= 12 else people[:12] + ["..."]
    print(len(part), "people:", ", ".join(shown))
Listing 9.5. The components of the friendship graph. code/grade-10/09-graphs-first-look/listings/components.py
$ python components.py
29 people: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, ...
10 people: 15, 16, 17, 19, 21, 22, 23, 24, 26, 27
1 people: 40
Output 9.5. Three components: 2929 people, 1010 people, and person 4040 alone.
The friendship graph of people 1 to 40, drawn in three groups by number. The orange edges join two groups. Persons 1 and 28, shaded, are the centre of the largest component; the group on the right is a component of its own, except 18, 20 and 25, whose friends are elsewhere.
The friendship graph of people 11 to 4040, drawn in three groups by number. The orange edges join two groups. Persons 11 and 2828, shaded, are the centre of the largest component; the group on the right is a component of its own, except 1818, 2020 and 2525, whose friends are elsewhere.

On a small weighted map, a shortest route can be found by hand with a frontier: keep the distance from the start of every place reached so far, and repeatedly settle the unsettled place with the smallest one, then look at the roads leaving it.

Part of the town’s road map, lengths in metres, from the Library (3) to the North Bridge (23). The route 3–24–1–23 is 3840 m. The road from the Town Square (1) to the Library is one-way, so the way back, 23–1–3, is only 2570 m.
Part of the town’s road map, lengths in metres, from the Library (3) to the North Bridge (23). The route 3–24–1–23 is 38403840 m. The road from the Town Square (1) to the Library is one-way, so the way back, 23–1–3, is only 25702570 m.

9.4 Radius, diameter and centre

Definition 9.8 (Eccentricity, radius, diameter, centre)

In a connected graph, the eccentricity of a vertex is its largest distance to another vertex. The radius of the graph is the smallest eccentricity, its diameter the largest one, and its centre the set of the vertices whose eccentricity is the radius.

Each vertex with its eccentricity. The radius is 2, the diameter 4, and the centre is C alone: from C, every vertex is at most two edges away.
Each vertex with its eccentricity. The radius is 22, the diameter 44, and the centre is C alone: from C, every vertex is at most two edges away.

The rumour of the opening question is a question about eccentricity: started by a person of eccentricity ee, it reaches everyone in that person’s component after ee days. On the largest component of the friendship graph:

from given_graphs import components, distances
from load_friends import load_friends

g = load_friends("friendships.csv")
from_1 = distances(g, 1)
for d in range(max(from_1.values()) + 1):
    print(f"at distance {d} from 1:", sorted(v for v in from_1 if from_1[v] == d))

largest = components(g)[0]
eccentricity = {v: max(distances(g, v).values()) for v in largest}
radius = min(eccentricity.values())
diameter = max(eccentricity.values())
print("radius", radius, " diameter", diameter)
print("centre:", [v for v in sorted(largest) if eccentricity[v] == radius])
print("eccentricity 7:", [v for v in sorted(largest) if eccentricity[v] == diameter])
Listing 9.6. Distances from person 11, then the radius, diameter and centre. code/grade-10/09-graphs-first-look/listings/distances_given.py
$ python distances_given.py
at distance 0 from 1: [1]
at distance 1 from 1: [5, 7, 10, 12, 28]
at distance 2 from 1: [2, 6, 8, 9, 11, 20, 34, 36, 37, 39]
at distance 3 from 1: [3, 4, 13, 14, 18, 25, 29, 30, 32, 33]
at distance 4 from 1: [31, 35, 38]
radius 4  diameter 7
centre: [1, 28]
eccentricity 7: [3, 4, 13, 14, 18, 31, 35, 38]
Output 9.6. Persons 11 and 2828 reach the whole component in 44 days; from the worst place it takes 77.

Remark 9.9

2929 people, each with at most 55 friends, and yet everyone is within 77 steps of everyone in the component. In large networks of people the distances are surprisingly small, a property called the small world: even with a few friends each, the number of people within kk steps multiplies at each step, so it grows very fast with kk.

Method 9.10 (Finding the centre of a small graph by hand)

  1. For each vertex, write the distance to every other vertex, by layers: its neighbours at 11, their new neighbours at 22, and so on.
  2. Its eccentricity is the number of the last layer.
  3. The radius is the smallest eccentricity, the diameter the largest; the centre is the vertices of eccentricity equal to the radius.

A map application turns a satellite position into a vertex of the road graph, and a route into a shortest path. The receiver gives its position as text, in a standard sentence format: Exercise 9.11 decodes one.

9.5 Exercises

Exercise 9.1 ★

A graph has 55 vertices with degrees 33, 22, 22, 22 and 11. How many edges does it have? Can a graph have degrees 33, 33, 11?

Solution

Solution of Exercise 9.1.

The degrees add up to 3+2+2+2+1=103 + 2 + 2 + 2 + 1 = 10, twice the number of edges: 55 edges. Degrees 33, 33, 11 add up to 77, an odd number, which cannot be twice a number of edges; besides, with 33 vertices a degree is at most 22.

Exercise 9.2 ★

Write the dictionary of sets of the undirected graph of the first drawing of the chapter (vertices A, B, C, D).

Solution

Solution of Exercise 9.2.

{"A": {"B", "C"}, "B": {"A", "C", "D"}, "C": {"A", "B"}, "D": {"B"}}: each of the four edges appears twice.

Exercise 9.3 ★

In the graph of eccentricities, give the distance from A to G and from E to F. Give two different shortest paths from B to D, or explain why there is only one.

Solution

Solution of Exercise 9.3.

A to G: A–B–C–F–G, distance 44. E to F: E–D–C–F, distance 33. From B to D there is only B–C–D: the graph has no cycle, so between two vertices there is a single path that does not repeat a vertex.

Exercise 9.4 ★

A graph has the edges 11–22, 22–33, 44–55 and the vertices 11 to 66. List its components. How many edges would make it connected, at least?

Solution

Solution of Exercise 9.4.

{1,2,3}\{1, 2, 3\}, {4,5}\{4, 5\} and {6}\{6\}. Each new edge joins at most two components into one, so going from 33 components to 11 takes at least 22 edges, for example 33–44 and 55–66.

Exercise 9.5 ★

Write degree(g, v), and use it to print the people of the friendship graph whose degree is 11.

Solution

Solution of Exercise 9.5.

return len(g[v]) (exercises/graph_tools.py). The people of degree 11 are 44, 1515, 1818, 2121, 2222, 2424, 2525, 2626, 3131 and 3535: the ten of the degree table.

Exercise 9.6 ★★

A function add_friendship(g, a, b) only writes g[a].add(b). After building the graph with it, which listing of the chapter detects the problem, and what does it print? Correct the function.

Solution

Solution of Exercise 9.6.

Each friendship is stored only at its first person, so the check of symmetry prints all 5050 friendships as edges without a reverse, instead of an empty list. The correct function also writes g[b].add(a) (exercises/graph_tools.py).

Exercise 9.7 ★★

Write is_path(g, seq), which says whether a list of vertices is a path of g. Check that [3, 2, 10, 1, 28] is a path of the friendship graph and [3, 1] is not.

Solution

Solution of Exercise 9.7.

Return False for an empty list or a first vertex outside the graph; otherwise check that every vertex but the last has the next one among its neighbours: all(seq[i + 1] in g[seq[i]] for i in range(len(seq) - 1)) (exercises/graph_tools.py). 33–22, 22–1010, 1010–11 and 11–2828 are friendships; 33–11 is not.

Exercise 9.8 ★★

Draw the graph with edges 11–22, 22–33, 33–44, 44–11, 11–55. Give the eccentricity of each vertex, the radius, the diameter and the centre.

Solution

Solution of Exercise 9.8.

Eccentricities: 11: 22, 22: 22, 33: 33, 44: 22, 55: 33 (the farthest pair is 33 and 55, through 22 or 44 and then 11). Radius 22, diameter 33, centre {1,2,4}\{1, 2, 4\}.

Exercise 9.9 ★★

In the directed drawing of the chapter, give the in-degree and out-degree of every vertex. Check that the in-degrees and the out-degrees have the same sum, and say why that is always so.

Solution

Solution of Exercise 9.9.

A: in 11, out 11; B: in 11, out 22; C: in 11, out 11; D: in 11, out 00. Both sums are 44, the number of edges: every directed edge leaves exactly one vertex and arrives at exactly one.

Exercise 9.10 ★★

Write edges_from_dict(g), which returns the set of the edges of an undirected graph, each written once as a pair (smaller, larger). Check the sum of the degrees on the friendship graph.

Solution

Solution of Exercise 9.10.

return {(min(a, b), max(a, b)) for a in g for b in g[a]}: each edge is met twice, once from each end, and the set keeps it once (exercises/graph_tools.py). The friendship graph gives 5050 edges, and the degrees add up to 100100.

Exercise 9.11 ★★

A satellite receiver sends lines of text such as

$GPGGA,093015.00,4807.0381,N,00131.5240,W,1,08,0.9,62.4,M,47.2,M,,*41

The fields after GPGGA are the time (hours, minutes, seconds), the latitude as degrees and minutes (ddmm.mmmm), N or S, the longitude as dddmm.mmmm, E or W, then the quality of the fix, the number of satellites, a precision figure and the altitude in metres. Give the time, and the latitude and longitude in decimal degrees, west and south counted negative. The two digits after * are a check: the exclusive or of the codes of all characters between $ and *, in hexadecimal. What is it for?

Solution

Solution of Exercise 9.11.

The time is 09:30:15 (on the satellites’ universal time). Latitude: 48+7.0381/60≈48.1173048 + 7.0381/60 \approx 48.11730 degrees north. Longitude: 1+31.5240/60=1.525401 + 31.5240/60 = 1.52540 degrees west, so −1.52540-1.52540 (exercises/nmea.py). The check lets the receiving program detect a line damaged on the way: if one character changed, the exclusive or almost surely differs from 41, and the line is thrown away.

Exercise 9.12 ★★★

Prove that in an undirected graph the sum of the degrees is twice the number of edges. Deduce that the number of vertices of odd degree is even.

Solution

Solution of Exercise 9.12.

Count the pairs (vertex, edge) where the edge touches the vertex. Counted by vertex, each vertex vv is in deg⁡(v)\deg(v) pairs, which gives the sum of the degrees. Counted by edge, each edge touches exactly two vertices, which gives 2∣E∣2|E|. So the sum of the degrees is 2∣E∣2|E|, an even number; the vertices of even degree add an even amount, so the odd degrees must add up to an even number too, and there is an even number of them.

Exercise 9.13 ★★★

Prove that in a connected graph, radius≤diameter≤2×radius\text{radius} \le \text{diameter} \le 2 \times \text{radius}. For the second inequality, take a vertex cc of the centre and two vertices aa and bb, and go from aa to bb through cc.

Solution

Solution of Exercise 9.13.

The radius is the smallest eccentricity and the diameter the largest, so radius≤diameter\text{radius} \le \text{diameter}. Take cc in the centre and any two vertices aa and bb. A path from aa to cc followed by a path from cc to bb is a path from aa to bb (it may be shortened if it repeats a vertex), so d(a,b)≤d(a,c)+d(c,b)≤radius+radiusd(a, b) \le d(a, c) + d(c, b) \le \text{radius} + \text{radius}. This holds for every pair, so the diameter is at most 2×radius2 \times \text{radius}. The graph of eccentricities reaches it: radius 22, diameter 44.

Exercise 9.14 ★★★

Write common_friends(g, a, b) with a set intersection, then triangles(g), the number of groups of three people who are all friends with one another. Why does adding the common friends of the two ends of every edge count each triangle three times? How many triangles has the friendship graph?

Solution

Solution of Exercise 9.14.

common_friends returns g[a] & g[b]. A triangle {x,y,z}\{x, y, z\} is found from its edge xx–yy (common friend zz), from xx–zz (common friend yy) and from yy–zz (common friend xx): three times, so the sum is divided by 33 (exercises/graph_tools.py). The friendship graph has 22 triangles.

Exercise 9.15 ★★★

A tiny web has five pages, P1 to P5, and links P1→\toP2, P1→\toP3, P2→\toP3, P4→\toP3, P5→\toP4, P3→\toP1. Rank the pages by in-degree. Then give each page one vote, which it shares equally among the pages it links to, and add the votes each page receives. Which page is first in each ranking? Explain why a search engine would rather count a link from an important page as worth more.

Solution

Solution of Exercise 9.15.

In-degrees: P3 has 33, P1, P2 and P4 have 11, P5 has 00. Votes: P1 gives 12\tfrac12 to P2 and 12\tfrac12 to P3; P2, P4 and P3 give their whole vote to P3, P3 and P1; P5 gives its vote to P4. Totals: P3 2.52.5, P1 11, P4 11, P2 0.50.5, P5 00. P3 is first both times. A link is a recommendation: one from a page that many others recommend says more than one from a page nobody links to, which is why search engines weigh links by the importance of the page they come from, and compute that importance the same way, over and over, until it settles.

9.6 Problem: Handshakes across Brenmoor

Problem 9.1

Weekend problem — how far apart the people of the largest group are

The program exercises/handshakes.py uses the given functions to compute the radius, the diameter and the centre of the largest component of the friendship graph, then again with one edge removed.

Part I — The graph.

  1. How many vertices and edges has the friendship graph? Check the sum of the degrees.
  2. Which people have the most friends? Which have exactly one?
  3. How many vertices have an odd degree? Is that consistent with Exercise 9.12?
  4. Give the neighbours of person 2828.

Part II — Components.

  1. List the sizes of the components.
  2. Can the rumour, started by person 11, reach person 2323? Why?
  3. Which four edges join two of the three groups of numbers? Which of them join two components?
  4. How many edges, at least, would make the whole graph connected?

Part III — Eccentricities.

  1. Using the output of the distance listing, give the eccentricity of person 11.
  2. Find two people at distance 77 from each other, and a shortest path between them.
  3. Which people are at distance 44 from person 11?
  4. How many days does the rumour take from person 33?

Part IV — The centre, and a missing bridge.

  1. Give the radius, the diameter and the centre of the largest component. Check radius≤diameter≤2×radius\text{radius} \le \text{diameter} \le 2 \times \text{radius}.
  2. Run the program. What happens to the components, the radius and the diameter when the friendship 11–2828 ends?
  3. Why does the centre move to 55 and 3737?
  4. Why does removing 55–3737 change nothing, while removing 11–2828 does?
  5. What does removing 1212–2020 do?
  6. If the library could ask one person to spread its news, whom should it ask, and how many days would the news take to reach the 2929 people?
  7. State the result: the diameter of the largest component, its centre, and what the loss of the friendship between the two central people does to the diameter.
Solution

Solution of Problem 9.1.

1. 4040 vertices and 5050 edges; the degrees add up to 100=2×50100 = 2 \times 50.

2. Most friends, 55: persons 11, 1212, 2323 and 2828. Exactly one: 44, 1515, 1818, 2121, 2222, 2424, 2525, 2626, 3131 and 3535.

3. Degrees 11, 33 and 55: 10+10+4=2410 + 10 + 4 = 24 people, an even number, as the exercise proves.

4. 11, 3434, 3636, 3737 and 3939.

5. 2929, 1010 and 11.

6. No: person 2323 is in the component of 1010 people, and no path joins it to the component of person 11.

7. 11–2828, 55–3737, 1212–2020 and 2525–3737. None joins two components: 2020 and 2525 have all their friends in the largest component.

8. 22: one edge joining the component of 1010 people to the largest one, and one joining person 4040.

9. 44: the farthest people, 3131, 3535 and 3838, are at distance 44.

10. For example 33 and 3131: 33–22–1010–11–2828–3434–2929–3131, seven edges.

11. 3131, 3535 and 3838.

12. Person 33 has eccentricity 77: 77 days.

13. Radius 44, diameter 77, centre {1,28}\{1, 28\}; 4≤7≤84 \le 7 \le 8.

14. The components stay 2929, 1010 and 11, but the radius becomes 55 and the diameter 99.

15. Without 11–2828, the two halves of the component are joined only through 55–3737; the people at the middle of that new route, 55 and 3737, become the closest to everyone.

16. Without 55–3737, the shortest paths still go through 11–2828, which is shorter: no distance that matters changes. Without 11–2828, every path between the two halves makes the detour through 55–3737.

17. Persons 1818 and 2020 become a component of their own: the largest component has 2727 people, with the same radius and diameter.

18. Person 11 or person 2828: the news reaches all 2929 people in 44 days.

19. The largest friendship component of Brenmoor has 2929 people, diameter 77, radius 44 and centre {1,28}\{1, 28\}. If the friendship between the two central people, 11 and 2828, ends, the component stays in one piece but its diameter grows from 77 to 99.

本章定义的术语

在术语表中查看全部 1050 个术语