Documente Academic
Documente Profesional
Documente Cultură
Programming
in Python
>>> Second Edition:
with Python 3
Maria Litvin
Phillips Academy, Andover, Massachusetts
Gary Litvin
Skylight Software, Inc.
Skylight Publishing
Andover, Massachusetts
Skylight Publishing
9 Bartlet Street, Suite 70
Andover, MA 01810
web:
e-mail:
http://www.skylit.com
sales@skylit.com
support@skylit.com
1 2 3 4 5 6 7 8 9 10
15 14 13 12 11 10
15 Graphs
15.1 Prologue
In the 1700s, the city of Knigsberg, then the capital of East Prussia near the Baltic
Sea, had seven bridges connecting the banks of the river Pregel with the banks of its
tributary and the Kniephof island in the center. No one remembers for sure how the
following puzzle came about: to find a path through the city that crosses each of the
seven bridges exactly once (Figure 15-1). Legend has it that many citizens took long
walks around the city on Sundays trying to solve the puzzle. (Believe it or not, there
were many lovers of puzzles in the 1700s, just as there are today.)
259
260
CHAPTER 15 ~ GRAPHS
The exact shape of the graph is not important you can move the vertices around
and stretch or bend the edges, as long as the topology of the graph (the particular
pairs of vertices connected by an edge) remains the same. The task is now to find a
continuous path in the graph that traces each edge exactly once. Such a path is called
an Euler path. Before you tackle the Seven Bridges puzzle, try to find an Euler path
in several other graphs (Figure 15-3) and come up with a rule to determine which
graphs have an Euler path and which dont (see Question 9 in Section 15.4).
15.1 ~ PROLOGUE
wolf
goat
cabbage
wolf
cabbage
goat
cabbage
wolf
cabbage
wolf
goat
wolf
goat
cabbage
goat
wolf
cabbage
goat
wolf
goat
cabbage
goat
wolf
cabbage
261
262
CHAPTER 15 ~ GRAPHS
A graph can have several edges connecting the same pair of vertices. Such graphs
are called multigraphs. The Seven Bridges graph (Figure 15-2) is an example. A
graph can also have an edge connecting a vertex to itself (Figure 15-5). Such edges
are called loops. In a simple graph (such as those shown in Figure 15-3), no more
than one edge connects a pair of vertices, and there are no loops.
Example 1
Describe the simple graph below as a set of vertices and a set of edges.
263
Solution
First we need to label the vertices of the graph to be able to refer to them. Lets use
the numbers from 1 to 4:
1
4
2
3
Now V = {1, 2,3, 4} , E = {(1, 2), (2,3), (3, 4), (4,1), (2, 4)} , G = (V , E ) . Or, in Python:
v = {1, 2, 3, 4}
e = {(1, 2), (2, 3), (3, 4), (4, 1), (2, 4)}
g = (v, e)
When a graph is used as a model for a real-life situation, its vertices may represent
different geographical locations, different objects, or different positions in a game.
But if you view a graph as an abstract mathematical object, the graph is defined only
by its topology; that is, by the configuration of its vertices and edges.
A simple graph in which every pair of vertices is connected by an edge is
called a complete graph.
Example 2
Draw K 4 and K 5 .
264
CHAPTER 15 ~ GRAPHS
Solution
K4
K5
A complete graph could be drawn differently, but from the point of view of graph
theory it would be essentially the same graph as long as it had the same number of
vertices and there was one edge connecting every vertex to every other vertex.
Another simple type of graph is one in which the vertices are arranged into a circular
sequence and each vertex is connected to two of its neighbors. (Think of a circle of
people holding hands.) Such a graph is called a cycle. A cycle with n vertices is
usually denoted by Cn .
Example 3
Draw C6 .
Solution
265
Exercises
1.
2.
Tag the vertices of the graph below with letters or numbers, then describe the
graph as a set of its vertices and a set of its edges.
4.
Which of the following graphs are simple graphs? Which are multigraphs?
Which have loops? 3
(a)
(b)
5.
6.
7.
(c)
(d)
266
CHAPTER 15 ~ GRAPHS
Example 1
Consider two graphs: G1 = (V1 , E1 ) and G2 = (V2 , E2 ) . The set of the
G2 isomorphic?
Solution
To find out, lets draw the two graphs:
E
D
C
At a first glance, they seem different, but a little bending (without breaking the
edges) will convince us that they in fact have the same configuration:
E
C
B
A
establishes
267
an
Note how we tagged the vertices of a graph to be able to refer to them. We used
letters for the first graph and numbers for the second. In general we can use any tags
or names.
An equivalence relation on the elements of a set breaks that set into non-overlapping
subsets, called equivalence classes. Any two elements in the same equivalence class
are equivalent to each other (that is, the equivalence relation holds for them), and
any two elements in different equivalence classes are not equivalent.
Since isomorphism is an equivalence relation between graphs, all graphs fall into
non-overlapping classes of isomorphic graphs.
268
CHAPTER 15 ~ GRAPHS
An equivalence class for the being connected by a path relation is a set of vertices
in a connected subgraph of G. Therefore, any graph is a union of non-intersecting
connected subgraphs (Figure 15-6).
Z
Y
Exercises
1.
(a)
and
(b)
and
(c)
and
269
2.
3.
How many different simple graphs with four vertices are there, if you count
all isomorphic graphs as one? How many of them are connected? 3
4.
6.
7.
8.
If an edge is a loop (connects a vertex to itself), that edge is counted twice in the
degree of that vertex. In a simple graph, the degree of a vertex is simply the number
of other vertices to which this vertex is connected.
270
CHAPTER 15 ~ GRAPHS
Example 1
What are the degrees of the vertices in the following multigraph?
A
B
E
D
Solution
A: 2; B: 4; C: 3; D: 3; E: 4.
If two graphs are isomorphic, the degrees of the corresponding vertices must match,
of course.
Exercises
1.
If a graph has n vertices, and d1 , d 2 ,..., d n are their degrees, what is the total
number of edges in that graph? 3
2.
3.
Can a graph have five vertices, each connected to exactly three others? Draw
an example or explain why not.
4.
5.
Prove that the only simple graph with n vertices and the degrees of all the
vertices equal to n-1 is K n . 3
6.
Prove that the only simple connected graph with three or more vertices and
the degrees of all the vertices equal to 2 is Cn . 3
271
7.
Give an example of two graphs with the same number of vertices, such that
the degrees of the vertices in the first graph match some permutation of the
degrees of the vertices in the second graph, but the graphs are not isomorphic
to each other.
8.
Show that in any group of six people there are either three who all know each
other or three who are all strangers to each other.
Hint:
9.
Recall that an Euler path traverses all the edges of a graph and passes
through each edge exactly once. Show that if a graph has an odd-degree
vertex, then an Euler path, if it exists, must begin or end at that vertex.
10.
11.
12.
13.
An Euler circuit in a graph begins and ends at the same vertex and traverses
every edge of the graph exactly once. Describe the necessary and sufficient
condition for a graph to have an Euler circuit.
14.
Show that for any n 3 there is a connected graph with n vertices that has an
Euler circuit (as defined in Question 13). 3
272
CHAPTER 15 ~ GRAPHS
15.
16.
17.
A Hamilton circuit in a graph starts and ends at the same vertex, goes along
the edges of the graph, and visits each vertex exactly once. Hamilton circuits
are named after an Irish mathematician, Sir William Rowan Hamilton
(1805-1865). In 1859, Hamilton designed a puzzle and sold it to a toy maker
in Dublin. The puzzle was a regular dodecahedron (a solid with twelve
pentagon-shaped faces and 20 vertices), made of wood. Each vertex was
labeled with the name of a prominent city. A player had to find a path with
the beginning and end at the same vertex that went along the edges and
visited each city exactly once. Solve Hamiltons original puzzle. Hint:
you can work with pencil and paper using a planar graph isomorphic to the
dodecahedron:
18.
Can you find a Hamilton circuit (as defined in Question 17) in the following
graph?
273
In a directed graph, there may be an arrow from vertex A to vertex B but not from B
to A, or there may be arrows in both directions (Figure 15-8).
274
CHAPTER 15 ~ GRAPHS
Example 1
Draw an undirected graph associated with the directed graph in Figure 15-8.
Solution
or
depending on how we agree to handle multiple edges between the same two vertices.
A weighted graph is a graph with numbers (weights) associated with its edges. For
example, a transit network can be represented by a weighted graph in which the
weights are distances between adjacent stations. A computer network can be
represented by a weighted graph in which weights represent the costs of transmitting
information over the links.
A typical task for a weighted graph is to find an optimal path between two given
vertices. The sum of the weights along such a path must be the smallest possible.
275
Example 2
5
1
A
1
1
2
2
4
B
3
Solution
You can try to list all possible paths, of course, but there are too many of them. A
more promising approach is to first find optimal paths to B from each neighbor of A
and mark the cost of each such optimal path:
7
5
B
4
Now we can add the cost of going from A to a neighbor to the cost of going from that
neighbor to B and find the best combination:
B
5
We can do this manually for a small graph, but obviously well need a computer
program for larger graphs.
276
CHAPTER 15 ~ GRAPHS
Exercises
1.
2.
A cycle in a directed graph is a path along the arrows that starts and ends at
the same vertex. Show that if every vertex in a directed graph has at least
one arrow coming out of it, then the graph has a cycle.
3.
Find an optimal path (with the smallest sum of weights along it) from A to B
in the following directed graph: 3
5
3
1
B
1
6
1
4.
277
In a famous puzzle dating back at least a thousand years, a farmer has a wolf,
a goat, and a cabbage. He needs to cross a river and transport his possessions
across, too, but his tiny boat can hold only him and one other object or
animal. How can he do it without endangering any of his possessions? (The
wolf would gobble up the goat in a minute, if left unattended, but she is
indifferent to cabbage, while the goat, on the contrary, loves cabbage. The
cabbage doesnt like anyone.)
(a)
(b)
Draw the arrows in the graph that correspond to the allowed river
crossings.
(c)
Find and describe the solution to the puzzle by finding a path from the
initial position (all on one bank) to the final position (all on the other
bank) along the edges of the graph. How many solutions are there?
5.
Four people need to cross a bridge in the dark. They all begin on the same
side and they have only one flashlight. A maximum of two people can cross
at one time. Any party that crosses, either 1 or 2 people, must have the
flashlight with them. The flashlight must be walked back and forth (it may
not be thrown, etc.). The four people walk at different speeds: it takes them
1, 2, 5, and 10 minutes, respectively, to cross from one side to the other.
What is the optimal strategy and the minimum time required for bringing all
four people across the bridge? Can it be accomplished in less than 19
minutes? Hint: Represent the problem as a weighted graph where the
vertices represent all possible positions and the edges represent allowed
crossings; assign a weight the duration of the crossing to each edge;
find the optimal path from the initial to the final position.
6.
278
CHAPTER 15 ~ GRAPHS
7.
15.6 Review
Connected graph
Degree of a vertex
Euler path
Euler circuit
Hamilton circuit
Directed graph
Weighted graph
Optimal path
G = (V , E )
Kn
Cn