Beruflich Dokumente
Kultur Dokumente
Algorithms
F O U R T H
E D I T I O N
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Undirected graphs
Graph. Set of vertices connected pairwise by edges.
Why study graph algorithms?
http://en.wikipedia.org/wiki/Internet
http://www.plosone.org/article/info:doi/10.1371/journal.pone.0004803
The Evolution of FCC Lobbying Coalitions by Pierre de Vries in JoSS Visualization Symposium 2010
Figure 1. Largest Connected Subcomponent of the Social Network in the Framingham Heart Study in the Year 2000.
Each circle (node) represents one person in the data set. There are 2200 persons in this subcomponent of the social
network. Circles with red borders denote women, and circles with blue borders denote men. The size of each circle
is proportional to the persons body-mass index. The interior color of the circles indicates the persons obesity status:
yellow denotes an obese person (body-mass index, 30) and green denotes a nonobese person. The colors of the
ties between the nodes indicate the relationship between them: purple denotes a friendship or marital tie and orange
denotes a familial tie.
The Spread of Obesity in a Large Social Network over 32 Years by Christakis and Fowler in New England Journal of Medicine, 2007
www.nejm.org
373
10
Graph applications
graph
vertex
edge
communication
telephone, computer
circuit
wire
mechanical
joint
financial
stock, currency
transactions
transportation
internet
class C network
connection
game
board position
legal move
social relationship
person, actor
neural network
neuron
synapse
protein network
protein
protein-protein interaction
molecule
atom
bond
11
Graph terminology
Path. Sequence of vertices connected by edges.
Cycle. Path whose first and last vertices are the same.
Two vertices are connected if there is a path between them.
vertex
cycle of
length 5
edge
path of
length 4
vertex of
degree 3
connected
components
Anatomy of a graph
12
13
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Graph representation
Graph drawing. Provides intuition about the structure of the graph.
16
Graph representation
Vertex representation.
symbol table
D
self-loop
parallel
edges
Anomalies.
Anomalies
17
Graph API
public class Graph
Graph(int V)
Graph(In in)
int V()
number of vertices
int E()
number of edges
String toString()
In in = new In(args[0]);
Graph G = new Graph(in);
for (int v = 0; v < G.V(); v++)
for (int w : G.adj(v))
StdOut.println(v + "-" + w);
string representation
18
tinyG.txt
13
E
13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
In in = new In(args[0]);
Graph G = new Graph(in);
for (int v = 0; v < G.V(); v++)
for (int w : G.adj(v))
StdOut.println(v + "-" + w);
19
4.1
Undirected Graphs
523
count self-loops
implementation
public static int degree(Graph G, int v)
{
int degree = 0;
for (int w : G.adj(v)) degree++;
return degree;
}
10
11
12
0
0
0
0
3
3
4
4
7
9
9
9
11
1
2
5
6
4
5
5
6
8
10
11
12
12
21
9
7
10
8
11
12
10
11
12
10
11
12
22
Bag objects
0
adj[]
0
2
3
4
5
6
7
representations
of the same edge
10
10
11
12
7
11
10
12
8
11
12
9
9
12
11
23
adjacency lists
( using Bag data type )
public Graph(int V)
{
this.V = V;
adj = (Bag<Integer>[]) new Bag[V];
for (int v = 0; v < V; v++)
adj[v] = new Bag<Integer>();
}
}
24
Graph representations
In practice. Use adjacency-lists representation.
sparse (E = 200)
dense (E = 1000)
25
Graph representations
In practice. Use adjacency-lists representation.
representation
space
add edge
edge between
v and w?
list of edges
adjacency matrix
V2
1*
adjacency lists
E+V
degree(v)
degree(v)
26
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Maze exploration
Maze graph.
Vertex = intersection.
Edge = passage.
intersection
passage
Tremaux exploration
30
Maze exploration
32
Maze exploration
33
Depth-first search
Goal. Systematically search through a graph.
Idea. Mimic maze exploration.
Typical applications.
boolean hasPathTo(int v)
Iterable<Integer> pathTo(int v)
10
11
12
tinyG.txt
13
E
13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
graph G
36
11
10
12
marked[]
edgeTo[v]
10
11
12
Depth-first search
Goal. Find all vertices connected to s (and a corresponding path).
Idea. Mimic maze exploration.
Algorithm.
Depth-first search
public class DepthFirstPaths
{
private boolean[] marked;
private int[] edgeTo;
private int s;
public DepthFirstPaths(Graph G, int s)
{
...
dfs(G, s);
}
private void dfs(Graph G, int v)
{
marked[v] = true;
for (int w : G.adj(v))
if (!marked[w])
{
dfs(G, w);
edgeTo[w] = v;
}
}
marked[v] = true
if v connected to s
edgeTo[v] = previous
vertex on path from s to v
}
39
set of marked
vertices
source
set of
unmarked
vertices
no such edge
can exist
40
edgeTo[]
0
1 2
2 0
3 2
4 3
5 3
path
5
3
2
0
5
3 5
2 3 5
0 2 3 5
http://xkcd.com/761/
42
Vertex: pixel.
Edge: between two adjacent gray pixels.
Blob: all pixels connected to given pixel.
43
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
6
8
0
2
2
1
0
3
3
0
3
5
standard d
tinyCG.txt
E
5
4
3
2
1
4
5
2
drawing w
adjacency lists
2
graph G
adj[]
0
0
46
3
5
edgeTo[] distTo[]
done
47
Breadth-first search
Depth-first search. Put unvisited vertices on a stack.
Breadth-first search. Put unvisited vertices on a queue.
Shortest path. Find path from s to t that uses fewest number of edges.
Breadth-first
maze exploration
48
1
0
2
3
3
5
graph
5
dist = 0
dist = 1
dist = 2
49
Breadth-first search
public class BreadthFirstPaths
{
private boolean[] marked;
private int[] edgeTo;
51
http://oracleofbacon.org
Include one vertex for each performer and one for each movie.
Connect a movie to all performers that appear in that movie.
Compute shortest path from s = Kevin Bacon.
Patrick
Allen
Caligola
Glenn
Close
John
Gielgud
The Stepford
Wives
Portrait
of a Lady
Murder on the
Orient Express
Donald
Sutherland
Cold
Mountain
Vernon
Dobtcheff
John
Belushi
The
Woodsman
movie
vertex
Jude
Animal
House
Kate
Winslet
Eternal Sunshine
of the Spotless
Mind
Kathleen
Quinlan
Joe Versus
the Volcano
performer
vertex
Apollo 13
Bill
Paxton
The River
Wild
Paul
Herbert
Meryl
Streep
Enigma
High
Noon
Lloyd
Bridges
Kevin
Bacon
Wild
Things
Grace
Kelly
To Catch
a Thief
The Eagle
Has Landed
Nicole
Kidman
An American
Haunting
Hamlet
Dial M
for Murder
Tom
Hanks
The Da
Vinci Code
Serretta
Wilson
Titanic
Yves
Aubert
Shane
Zaza
53
movies.txt
V and E
not explicitly
specified
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Connectivity queries
Def. Vertices v and w are connected if there is a path between them.
Goal. Preprocess graph to answer queries of the form is v connected to w?
in constant time.
public class CC
CC(Graph G)
boolean connected(int v, int w)
int count()
int id(int v)
Connected components
The relation "is connected to" is an equivalence relation:
Reflexive: v is connected to v.
Symmetric: if v is connected to w, then w is connected to v.
Transitive: if v connected to w and w connected to x, then v connected to x.
Def. A connected component is a maximal set of connected vertices.
10
11
12
5
3 connected components
v
0
1
2
3
4
5
6
7
8
9
10
11
12
id[]
0
0
0
0
0
0
0
1
1
2
2
2
2
Connected components
Def. A connected component is a maximal set of connected vertices.
63 connected components
59
Connected components
Goal. Partition vertices into connected components.
Connected components
Initialize all vertices v as unmarked.
For each unmarked vertex v, run DFS to identify all
tinyG.txt
13
E
13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
13
E
13
0 5
mediumG.txt
4 3
250 0 1
E
12739 12
4
244 6246
4
239 5240
2
238 0245
12
235 11
238
9 10
233 240
0 6
232 248
7 8
231 9248
11
229 5249
3
228 241
226 231
...
(1261 additional lines)
I
60
11
10
12
marked[]
id[]
10
11
12
graph G
61
11
10
12
marked[]
id[]
10
11
12
done
62
}
63
number of components
id of component containing v
64
Vertex: pixel.
Edge: between two adjacent pixels with grayscale value 70.
Blob: connected component of 20-30 pixels.
black = 0
white = 255
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Graph-processing challenge 1
Problem. Is a graph bipartite?
How difficult?
2
3
6
4
2
3
6
4
0-1
0-2
0-5
0-6
1-3
2-3
2-4
4-5
4-6
0-1
0-2
0-5
0-6
1-3
2-3
2-4
4-5
4-6
{ 0, 3, 4 }
69
70
Graph-processing challenge 2
Problem. Find a cycle.
How difficult?
2
3
6
4
0-1
0-2
0-5
0-6
1-3
2-3
2-4
4-5
4-6
0-5-4-6-0
71
Bridges of Knigsberg
The Seven Bridges of Knigsberg. [Leonhard Euler 1736]
in Knigsberg in Prussia, there is an island A, called the
Kneiphof; the river which surrounds it is divided into two branches ...
and these branches are crossed by seven bridges. Concerning these
bridges, it was asked whether anyone could arrange a route in such a
way that he could cross each bridge once and only once.
Euler tour. Is there a (general) cycle that uses each edge exactly once?
Answer. A connected graph is Eulerian iff all vertices have even degree.
72
Graph-processing challenge 3
Problem. Find a (general) cycle that uses every edge exactly once.
How difficult?
2
3
6
4
0-1
0-2
0-5
0-6
1-2
2-3
2-4
3-4
4-5
4-6
0-1-2-3-4-2-0-6-4-5-0
Eulerian tour
(classic graph-processing problem)
73
Graph-processing challenge 4
Problem. Find a cycle that visits every vertex exactly once.
How difficult?
2
3
6
4
0-1
0-2
0-5
0-6
1-2
2-6
3-4
3-5
4-5
4-6
0-5-3-4-6-2-1-0
Hamiltonian cycle
(classical NP-complete problem)
74
Graph-processing challenge 5
Problem. Are two graphs identical except for vertex names?
How difficult?
2
3
6
4
3
2
4
1
5
0
0-1
0-2
0-5
0-6
3-4
3-5
4-5
4-6
0-4
0-5
0-6
1-4
1-5
2-4
3-4
5-6
Graph-processing challenge 6
Problem. Lay out a graph in the plane without crossing edges?
1
2
0
How difficult?
4
5
0-1
0-2
0-5
0-6
3-4
3-5
4-5
4-6
2
3
6
4
76
Algorithms
R OBERT S EDGEWICK | K EVIN W AYNE
http://algs4.cs.princeton.edu
depth-first search
breadth-first search
connected components
challenges
Algorithms
Algorithms
F O U R T H
E D I T I O N
depth-first search
breadth-first search
connected components
challenges