0% found this document useful (0 votes)
13 views19 pages

41UndirectedGraphs 2x2

The document discusses undirected graphs, covering their definitions, applications, and various algorithms such as depth-first search and breadth-first search. It highlights the importance of graph algorithms in practical applications and provides examples of graph representations and processing problems. Additionally, it includes a Java implementation of a graph API and explores maze exploration as a practical application of graph theory.

Uploaded by

Tăng Hà
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

41UndirectedGraphs 2x2

The document discusses undirected graphs, covering their definitions, applications, and various algorithms such as depth-first search and breadth-first search. It highlights the importance of graph algorithms in practical applications and provides examples of graph representations and processing problems. Additionally, it includes a Java implementation of a graph API and explores maze exploration as a practical application of graph theory.

Uploaded by

Tăng Hà
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Algorithms R OBERT S EDGEWICK | K EVIN W AYNE

4.1 U NDIRECTED G RAPHS 4.1 U NDIRECTED G RAPHS


‣ introduction ‣ introduction
‣ graph API ‣ graph API
‣ depth-first search ‣ depth-first search
Algorithms Algorithms
‣ breadth-first search ‣ breadth-first search
F O U R T H E D I T I O N

R OBERT S EDGEWICK | K EVIN W AYNE


‣ connected components R OBERT S EDGEWICK | K EVIN W AYNE
‣ connected components
http://algs4.cs.princeton.edu ‣ challenges http://algs4.cs.princeton.edu ‣ challenges

Undirected graphs Border graph of 48 contiguous United States

Graph. Set of vertices connected pairwise by edges.

Why study graph algorithms?


Thousands of practical applications.
Hundreds of graph algorithms known.
Interesting and broadly useful abstraction.
Challenging branch of computer science and discrete math.

3 4
Protein-protein interaction network Map of science clickstreams

Reference: Jeong et al, Nature Review | Genetics


http://www.plosone.org/article/info:doi/10.1371/journal.pone.0004803
5 6

10 million Facebook friends The evolution of FCC lobbying coalitions

"Visualizing Friendships" by Paul Butler

8 “The Evolution of FCC Lobbying Coalitions” by Pierre de Vries in JoSS Visualization Symposium 2010 9
use of a lagged independent variable for an alter’s the spread of obesity by adding variables for the
weight status controlled for homophily.25 The smoking status of egos and alters at times t and
key variable of interest was an alter’s obesity at t + 1 to the foregoing models. We also analyzed
time t + 1. A significant coefficient for this vari- the role of geographic distance between egos
Framingham heart study
able would suggest either that an alter’s weight
affected an ego’s weight or that an ego and an
and alters by adding such a variable.
We calculated 95% confidence intervals by sim-
The Internet as mapped by the Opte Project
alter experienced contemporaneous events affect- ulating the first difference in the alter’s contem-

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 person’s body-mass index. The interior color of the circles indicates the person’s 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.
http://en.wikipedia.org/wiki/Internet

“The Spread of Obesity in a Large Social Network over 32 Years” by Christakis and Fowler in New England Journal of Medicine, 2007 10 11
n engl j med 357;4 www.nejm.org july 26, 2007 373

Graph applications Graph terminology

Path. Sequence of vertices connected by edges.


graph vertex edge
Cycle. Path whose first and last vertices are the same.
communication telephone, computer fiber optic cable

circuit gate, register, processor wire Two vertices are connected if there is a path between them.

mechanical joint rod, beam, spring


vertex
edge
financial stock, currency transactions cycle of
length 5
transportation intersection street
path of
internet class C network connection length 4

game board position legal move vertex of


degree 3
social relationship person friendship

neural network neuron synapse


connected
protein network protein protein-protein interaction components

molecule atom bond

12 Anatomy of a graph 13
Some graph-processing problems

problem description

s-t path Is there a path between s and t ?

shortest s-t path What is the shortest path between s and t ?

cycle Is there a cycle in the graph ?


4.1 U NDIRECTED G RAPHS
Euler cycle Is there a cycle that uses each edge exactly once ? ‣ introduction
Hamilton cycle Is there a cycle that uses each vertex exactly once ? ‣ graph API
‣ depth-first search
connectivity Is there a way to connect all of the vertices ?
Algorithms
biconnectivity Is there a vertex whose removal disconnects the graph ? ‣ breadth-first search
planarity Can the graph be drawn in the plane with no crossing edges ? R OBERT S EDGEWICK | K EVIN W AYNE
‣ connected components
http://algs4.cs.princeton.edu ‣ challenges
graph isomorphism Do two adjacency lists represent the same graph ?

Challenge. Which graph problems are easy? difficult? intractable?


14

Graph representation Graph representation

Graph drawing. Provides intuition about the structure of the graph. Vertex representation.
This lecture: use integers between 0 and V – 1.
Applications: convert between names and integers with symbol table.

A 0

B C G 1 2 6

symbol table

D E 3 4

F 5
two drawings of the same graph
Two drawings of the same graph

self-loop parallel
edges
Anomalies.
Caveat. Intuition can be misleading.
Anomalies
16 17
Two drawings of the same graph
Graph API Graph API: sample client

Graph input format.


public class Graph

Graph(int V) create an empty graph with V vertices tinyG.txt % java Test tinyG.txt
mediumG.txt
V V 0-6250
13
E E
Graph(In in) create a graph from input stream 13 0-21273
0 5 244 246
0-1
void addEdge(int v, int w) 4 3 239 240
add an edge v-w 0-5238 245
0 1
9 12 1-0235 238
Iterable<Integer> adj(int v) vertices adjacent to v 6 4 2-0233 240
5 4 232 248
3-5
int V() number of vertices 0 2 231 248
11 12 3-4229 249
int E() number of edges 9 10 ⋮ 228 241
0 6 226 231
12-11
7 8 ...
9 11 12-9
(1261 additional lines)
5 3
Input format for Graph constructor (two examples)

In in = new In(args[0]); read graph from In in = new In(args[0]); read graph from
Graph G = new Graph(in); input stream Graph G = new Graph(in); input stream

for (int v = 0; v < G.V(); v++) print out each


for (int v = 0; v < G.V(); v++) print out each
for (int w : G.adj(v)) edge (twice) for (int w : G.adj(v)) edge (twice)
StdOut.println(v + "-" + w); StdOut.println(v + "-" + w);
18 19

Typical graph-processing code Set-of-edges graph representation

Maintain a list of the edges (linked list or array).


public class Graph

Graph(int V) create an empty graph with V vertices

Graph(In in) create a graph from input stream


0
void addEdge(int v, int w) add an edge v-w 0 1
0 2
Iterable<Integer> adj(int v) vertices adjacent to v 1 2 6 0 5
int V() number of vertices 0 6
3 4 3 4
int E() number of edges 3 5
5 4 5
4 6
// degree of vertex v in graph G 7 8
9 10
public static int degree(Graph G, int v) 9 10
{ 7 8 9 11
int degree = 0; 9 12
11 12
for (int w : G.adj(v)) 11 12
degree++;
return degree;
} Q. How long to iterate over vertices adjacent to v ?
20 21
Adjacency-matrix graph representation Adjacency-list graph representation

Maintain a two-dimensional V-by-V boolean array; Maintain vertex-indexed array of lists.


for each edge v–w in graph: adj[v][w] = adj[w][v] = true.
6 2 1 5

0
two entries Bag objects
0 for each edge 0
0

0 1 2 3 4 5 6 7 8 9 10 11 12 adj[]
0 5 4
1 2 6 0 0 1 1 0 0 1 1 0 0 0 0 0 0 1 2 6 1
1 1 0 0 0 0 0 0 0 0 0 0 0 0 2 5 6 3
2 1 0 0 0 0 0 0 0 0 0 0 0 0 3
3 4 3 0 0 0 0 1 1 0 0 0 0 0 0 0 3 4 4 3 4 0
4 0 0 0 1 0 1 1 0 0 0 0 0 0 5
6 0 4
5 5 1 0 0 1 1 0 0 0 0 0 0 0 0 5 7
6 1 0 0 0 1 0 0 0 0 0 0 0 0 8
8
7 0 0 0 0 0 0 0 0 1 0 0 0 0 representations
9 of the same edge
9 10 8 0 0 0 0 0 0 0 1 0 0 0 0 0 9 10 10 7
9 0 0 0 0 0 0 0 0 0 0 1 1 1 11
7 8 10 0 0 0 0 0 0 0 0 0 1 0 0 0 7 8 12 11 10 12

11 12 11 0 0 0 0 0 0 0 0 0 1 0 0 1 11 12 9
12 0 0 0 0 0 0 0 0 0 1 0 1 0
9 12

Q. How long to iterate over vertices adjacent to v ? Q. How long to iterate over vertices adjacent to v ? 11 9

22 Adjacency-lists representation (undirected graph) 23

Graph representations Graph representations

In practice. Use adjacency-lists representation. In practice. Use adjacency-lists representation.


Algorithms based on iterating over vertices adjacent to v. Algorithms based on iterating over vertices adjacent to v.
Real-world graphs tend to be sparse. Real-world graphs tend to be sparse.
huge number of vertices, huge number of vertices,
small average vertex degree small average vertex degree

sparse (E = 200) dense (E = 1000)

edge between iterate over vertices


representation space add edge
v and w? adjacent to v?

list of edges E 1 E E

adjacency matrix V2 1* 1 V

adjacency lists E+V 1 degree(v) degree(v)

Two graphs (V = 50) * disallows parallel edges

24 25
Adjacency-list graph representation: Java implementation

public class Graph


{
private final int V; adjacency lists
private Bag<Integer>[] adj; ( using Bag data type )

public Graph(int V)
{ 4.1 U NDIRECTED G RAPHS
this.V = V;
create empty graph
adj = (Bag<Integer>[]) new Bag[V]; with V vertices ‣ introduction
for (int v = 0; v < V; v++)
adj[v] = new Bag<Integer>(); ‣ graph API
}
‣ depth-first search
Algorithms
public void addEdge(int v, int w)
‣ breadth-first search
{ add edge v-w
adj[v].add(w); (parallel edges and
R OBERT S EDGEWICK | K EVIN W AYNE
‣ connected components
adj[w].add(v); self-loops allowed)

} http://algs4.cs.princeton.edu ‣ challenges

public Iterable<Integer> adj(int v) iterator for vertices adjacent to v

{ return adj[v]; }
}
26

Maze exploration Trémaux maze exploration

Maze graph. Algorithm.


Vertex = intersection. Unroll a ball of string behind you.
Edge = passage. Mark each visited intersection and each visited passage.
Retrace steps when no unvisited options.

intersection passage

Tremaux exploration
Goal. Explore every intersection in the maze.
28 29
Trémaux maze exploration Maze exploration: easy

Algorithm.
Unroll a ball of string behind you.
Mark each visited intersection and each visited passage.
Retrace steps when no unvisited options.

First use? Theseus entered Labyrinth to kill the monstrous Minotaur;


Ariadne instructed Theseus to use a ball of string to find his way back out.

The Labyrinth (with Minotaur) Claude Shannon (with Theseus mouse)

30 31

Maze exploration: medium Maze exploration: challenge for the bored

32 33
Depth-first search Depth-first search demo

Goal. Systematically traverse a graph. To visit a vertex v :


Idea. Mimic maze exploration. function-call stack acts as ball of string Mark vertex v as visited.
Recursively visit all unmarked vertices adjacent to v.

DFS (to visit a vertex v)


tinyG.txt
0 7 8 V
Mark v as visited. 13
E
13
Recursively visit all unmarked 0 5
vertices w adjacent to v. 4 3
0 1
1 2 6 9 10 9 12
6 4
5 4
0 2
11 12
Typical applications. 3 4 11 12
9 10
Find all vertices connected to a given source vertex. 0 6
7 8
Find a path between two vertices. 5
9 11
5 3
I

Design challenge. How to implement? graph G

35

Depth-first search demo Design pattern for graph processing

To visit a vertex v : Design pattern. Decouple graph data type from graph processing.
Mark vertex v as visited. Create a Graph object.
Recursively visit all unmarked vertices adjacent to v. Pass the Graph to a graph-processing routine.
Query the graph-processing routine for information.
0 7 8 v marked[] edgeTo[]

0 T –
public class Paths
1 T 0
2 T 0 Paths(Graph G, int s) find paths in G from source s
1 2 6 9 10 3 T 5
4 T 6 boolean hasPathTo(int v) is there a path from s to v?
5 T 4
6 T 0 Iterable<Integer> pathTo(int v) path from s to v; null if no such path
3 4 11 12 7 F –
8 F –
9 F –
5 10 F – Paths paths = new Paths(G, s);
11 F – for (int v = 0; v < G.V(); v++)
12 F – if (paths.hasPathTo(v))
print all vertices
StdOut.println(v); connected to s
vertices reachable from 0

36 37
Depth-first search: data structures Depth-first search: Java implementation

To visit a vertex v : public class DepthFirstPaths


Mark vertex v as visited. { marked[v] = true
private boolean[] marked; if v connected to s
Recursively visit all unmarked vertices adjacent to v.
private int[] edgeTo; edgeTo[v] = previous
private int s; vertex on path from s to v

public DepthFirstPaths(Graph G, int s)


Data structures. {
... initialize data structures
Boolean array marked[] to mark visited vertices.
dfs(G, s); find vertices connected to s
Integer array edgeTo[] to keep track of paths. }
(edgeTo[w] == v) means that edge v-w taken to visit w for first time
private void dfs(Graph G, int v)
Function-call stack for recursion. {
recursive DFS does the work

marked[v] = true;
for (int w : G.adj(v))
if (!marked[w])
{
dfs(G, w);
edgeTo[w] = v;
}
}
}
39

Depth-first search: properties Depth-first search: properties

Proposition. DFS marks all vertices connected to s in time proportional to Proposition. After DFS, can check if vertex v is connected to s in constant
the sum of their degrees (plus time to initialize the marked[] array). time and can find v–s path (if one exists) in time proportional to its length.

Pf. [correctness] source set of marked Pf. edgeTo[] is parent-link representation of a tree rooted at vertex s.
vertices
If w marked, then w connected to s (why?) s
If w connected to s, then w marked.
(if w unmarked, then consider last edge
public boolean hasPathTo(int v)
on a path from s to w that goes from a v { return marked[v]; }
no such edge
set of can exist
marked vertex to an unmarked one). unmarked edgeTo[]
public Iterable<Integer> pathTo(int v)
vertices x 0
{
1 2
if (!hasPathTo(v)) return null; 2 0
Pf. [running time] Stack<Integer> path = new Stack<Integer>(); 3 2
Each vertex connected to s is visited once. for (int x = v; x != s; x = edgeTo[x]) 4 3
w path.push(x); 5 3
path.push(s); x path
return path; 5 5
} 3 3 5
2 2 3 5
0 0 2 3 5

Trace of pathTo() computation


40 41
Depth-first search application: flood fill Depth-first search application: preparing for a date

Challenge. Flood fill (Photoshop magic wand).


Assumptions. Picture has millions to billions of pixels.

Solution. Build a grid graph (implicitly).


Vertex: pixel.
Edge: between two adjacent gray pixels.
Blob: all pixels connected to given pixel. http://xkcd.com/761/

42 43

Breadth-first search demo

Repeat until queue is empty:


Remove vertex v from queue.
Add to queue all unmarked vertices adjacent to v and mark them.

4.1 U NDIRECTED G RAPHS tinyCG.txt standard drawin


0 2
V
‣ introduction 6
8
E

‣ graph API 1
0
2
5
4
2 3
‣ depth-first search
Algorithms 1
0
2
1
drawing with bo

‣ breadth-first search 3 3 4
3 5

R OBERT S EDGEWICK | K EVIN W AYNE


‣ connected components 5 4 0 2

http://algs4.cs.princeton.edu ‣ challenges
adjacency lists
2 1

graph G
0 2
adj[]
45
0
0 1
1
Breadth-first search demo Breadth-first search

Repeat until queue is empty: Repeat until queue is empty:


Remove vertex v from queue. Remove vertex v from queue.
Add to queue all unmarked vertices adjacent to v and mark them. Add to queue all unmarked vertices adjacent to v and mark them.

0 2 BFS (from source vertex s)


v edgeTo[] distTo[]

0 – 0 Put s onto a FIFO queue, and mark s as visited.


1 0 1 Repeat until the queue is empty:
1 2 0 1 - remove the least recently added vertex v
3 2 2
- add each of v's unvisited neighbors to the queue,
4 2 2
3 5 0 1
and mark them as visited.
5 4

Breadth-first
maze exploration

done

46 47

Breadth-first search: Java implementation Breadth-first search properties

public class BreadthFirstPaths


Q. In which order does BFS examine vertices?
{ A. Increasing distance (number of edges) from s.
private boolean[] marked;
private int[] edgeTo;
private int[] distTo; queue always consists of ≥ 0 vertices of distance k from s,
followed by ≥ 0 vertices of distance k+1

private void bfs(Graph G, int s) {


Queue<Integer> q = new Queue<Integer>(); initialize FIFO queue of
q.enqueue(s); vertices to explore Proposition. In any connected graph G, BFS computes shortest paths
marked[s] = true;
distTo[s] = 0; from s to all other vertices in time proportional to E + V.
while (!q.isEmpty()) {
int v = q.dequeue();
for (int w : G.adj(v)) {
if (!marked[w]) { 1
4
q.enqueue(w); s 0 2
found new vertex w
marked[w] = true;
via edge v-w
edgeTo[w] = v;
distTo[w] = distTo[v] + 1; 1 0 2
} 3
} 3
} 5 4
5
}
}
graph G dist = 0 dist = 1 dist = 2
48 49
Breadth-first search application: routing Breadth-first search application: Kevin Bacon numbers

Fewest number of hops in a communication network.

Endless Games board game

ARPANET, July 1977


SixDegrees iPhone App
http://oracleofbacon.org

50 51

Kevin Bacon graph Breadth-first search application: Erdös numbers

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 Dial M Grace


Caligola Kelly
Allen for Murder

Glenn The Stepford


Close Wives High
To Catch Noon
a Thief
John
Gielgud
Portrait Lloyd
of a Lady The Eagle Bridges
Nicole Has Landed
Kidman

Murder on the
Orient Express
Cold Donald
Sutherland Kathleen Joe Versus
Mountain
Quinlan the Volcano

An American John Animal


Hamlet Haunting Belushi House performer
Apollo 13 vertex
Vernon
Dobtcheff
The
Woodsman Kevin
Bacon Tom
Hanks
Bill
movie Paxton
Wild
vertex Things The River
Jude Wild
The Da
Paul
Vinci Code
Herbert
Meryl
Enigma Streep Serretta
Kate Wilson
Winslet Yves
Titanic
Aubert Shane
Eternal Sunshine Zaza
of the Spotless
Mind

hand-drawing of part of the Erdös graph by Ron Graham


52 53
V and E
movies.txt
not explicitly
specified
...
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.

4.1 U NDIRECTED G RAPHS


public class CC
‣ introduction CC(Graph G) find connected components in G
‣ graph API
boolean connected(int v, int w) are v and w connected?
‣ depth-first search
Algorithms int count() number of connected components
‣ breadth-first search
int id(int v) component identifier for v

R OBERT S EDGEWICK | K EVIN W AYNE


‣ connected components (between 0 and count() - 1)

http://algs4.cs.princeton.edu ‣ challenges

Union-Find? Not quite.


Depth-first search. Yes. [next few slides]
55

Connected components Connected components

The relation "is connected to" is an equivalence relation: Def. A connected component is a maximal set of connected vertices.
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.


v id[]
0 0
7 8
0 1 0
2 0
3 0
1 2 6 4 0
9 10 5 0
6 0
3 4 7 1
11 12 8 1
5 9 2
10 2
3 connected components 11 2
12 2

Remark. Given connected components, can answer queries in constant time.


63 connected components
56 57
Connected components Connected components demo

Goal. Partition vertices into connected components. To visit a vertex v :


Mark vertex v as visited.
Recursively visit all unmarked vertices adjacent to v.
Connected components

Initialize all vertices v as unmarked. v marked[] id[]


0 7 8
0 F –
For each unmarked vertex v, run DFS to identify all tinyG.txt mediumG.txt 1 F –
vertices discovered as part of the same component. V V 250 2 F –
13
E E
13 1 1273 2 6 9 10 3 F –
0 5 244 246
tinyG.txt mediumG.txt 4 F –
4 3 239 240
V V 250 0 1 5 F –
13 238 245
E E
13 12739 12 235 238 6 F –
0 5 244 6246
4 233
3 240 4 11 12 7 F –
4 3 239 5240
4 232 248
231 248 8 F –
0 1 238 0245
2
11 12 229 249 9 F –
9 12 235 238
9 10 5 228 241 10 F –
6 4 233 240
0 6 226 231
5 4 232 7248
8 ... 11 F –
0 2 231 9248
11 (1261 additional lines) 12 F –
11 12 229 5249
3
9 10 228 241 Input formatgraph
for Graph
G constructor (two examples)
0 6 226 231
7 8 ... 58 59

9 11 (1261 additional lines)


5 3
Input format for Graph constructor (two examples)
Connected components demo Finding connected components with DFS

To visit a vertex v : public class CC


{
Mark vertex v as visited.
private boolean[] marked;
Recursively visit all unmarked vertices adjacent to v. private int[] id; id[v] = id of component containing v
private int count; number of components

v marked[] id[] public CC(Graph G)


0 7 8
{
0 T 0 marked = new boolean[G.V()];
1 T 0 id = new int[G.V()];
2 T 0 for (int v = 0; v < G.V(); v++)
1 2 6 9 10 3 T 0 {
4 T 0 if (!marked[v])
{ run DFS from one vertex in
5 T 0
dfs(G, v); each component
6 T 0
count++;
3 4 11 12 7 T 1 }
8 T 1 }
9 T 2 }
5 10 T 2
11 T 2 public int count() see next slide
public int id(int v)
12 T 2
public boolean connected(int v, int w)
private void dfs(Graph G, int v)
done
}
60 61
Finding connected components with DFS (continued) Connected components application: study spread of STDs

public int count()


number of components
{ return count; }

public int id(int v) id of component containing v


{ return id[v]; }

public boolean connected(int v, int w) v and w connected iff same id


{ return id[v] == id[w]; }

private void dfs(Graph G, int v)


{
marked[v] = true;
all vertices discovered in
id[v] = count; same call of dfs have same id
for (int w : G.adj(v))
if (!marked[w])
dfs(G, w);
}

Relationship graph at "Jefferson High"

Peter Bearman, James Moody, and Katherine Stovel. Chains of affection: The structure of adolescent
romantic and sexual networks. American Journal of Sociology, 110(1): 44–99, 2004.
62 63

Connected components application: particle detection

Particle detection. Given grayscale image of particles, identify "blobs."


Vertex: pixel.
Edge: between two adjacent pixels with grayscale value ≥ 70.
Blob: connected component of 20-30 pixels.
black = 0
white = 255
4.1 U NDIRECTED G RAPHS
‣ introduction
‣ graph API
‣ depth-first search
Algorithms
‣ breadth-first search

R OBERT S EDGEWICK | K EVIN W AYNE


‣ connected components
http://algs4.cs.princeton.edu ‣ challenges

Particle tracking. Track moving particles over time.


64
Graph-processing challenge 1 Bipartiteness application: is dating graph bipartite?

Problem. Is a graph bipartite?

0 0-1
0-2
0-5
1 2 6
0-6
1-3
How difficult? 3 4 2-3
Any programmer could do it. 2-4
5 4-5
✓ Typical diligent algorithms student could do it. 4-6
Hire an expert.
Intractable. simple DFS-based solution
0
(see textbook) 0-1
No one knows. 0-2
0-5
Impossible. 1 2 6
0-6
1-3
3 4 2-3
2-4
5 4-5
Image created by Mark Newman.
4-6
{ 0, 3, 4 }

66 67

Graph-processing challenge 2 Bridges of Königsberg

Problem. Find a cycle. The Seven Bridges of Königsberg. [Leonhard Euler 1736]

“ … in Königsberg in Prussia, there is an island A, called the


0 0-1
0-2 Kneiphof; the river which surrounds it is divided into two branches ...
0-5 and these branches are crossed by seven bridges. Concerning these
1 2 6
0-6
1-3 bridges, it was asked whether anyone could arrange a route in such a
How difficult? 3 4 2-3 way that he could cross each bridge once and only once. ”
Any programmer could do it. 2-4
5 4-5
✓ Typical diligent algorithms student could do it. 4-6
Hire an expert. 0-5-4-6-0

Intractable. simple DFS-based solution


(see textbook)
No one knows.
Impossible.

Euler cycle. Is there a (general) cycle that uses each edge exactly once?
Answer. A connected graph is Eulerian iff all vertices have even degree.

68 69
Graph-processing challenge 3 Graph-processing challenge 4

Problem. Find a (general) cycle that uses every edge exactly once. Problem. Find a cycle that visits every vertex exactly once.

0 0-1 0 0-1
0-2 0-2
0-5 0-5
1 2 6 1 2 6
0-6 0-6
1-2 1-2
How difficult? 3 4
How difficult? 3 4
2-3 2-6
Any programmer could do it. 2-4 Any programmer could do it. 3-4
5 3-4 5 3-5
✓ Typical diligent algorithms student could do it. 4-5
Typical diligent algorithms student could do it. 4-5
Hire an expert. 4-6 Hire an expert. 4-6
0-1-2-3-4-2-0-6-4-5-0 0-5-3-4-6-2-1-0
Intractable. Euler cycle ✓ Intractable.
(classic graph-processing problem) Hamilton cycle
No one knows. No one knows. (classical NP-complete problem)

Impossible. Impossible.

70 71

Graph-processing challenge 5 Graph-processing challenge 6

Problem. Are two graphs identical except for vertex names? Problem. Lay out a graph in the plane without crossing edges?

0 0-1 1 0-1
0-2 0-2
2
0-5 0-5
1 2 6 0
0-6 0-6
6
3-4 3-4
How difficult? 3 4
How difficult? 3
3-5 4 3-5
Any programmer could do it. 4-5 Any programmer could do it. 4-5
5 4-6 5 4-6
Typical diligent algorithms student could do it. Typical diligent algorithms student could do it.
Hire an expert. ✓ Hire an expert.
Intractable. 3 0-4 Intractable. 0
linear-time DFS-based planarity algorithm
✓ No one knows. 2
0-5 No one knows. discovered by Tarjan in 1970s
0-6
Impossible. 4 1-4 Impossible. (too complicated for most practitioners) 1 2 6
graph isomorphism is 1
6 1-5
longstanding open problem
5 2-4 3 4
3-4
0 5-6 5

0↔4, 1↔3, 2↔2, 3↔6, 4↔5, 5↔0, 6↔1

72 73
Graph traversal summary

BFS and DFS enables efficient solution of many (but not all) graph problems.

problem BFS DFS time

path between s and t ✔ ✔ E+V

shortest path between s and t ✔ E+V

connected components ✔ ✔ E+V

biconnected components ✔ E+V

cycle ✔ ✔ E+V

Euler cycle ✔ E+V

Hamilton cycle 2 1.657 V


bipartiteness ✔ ✔ E+V

planarity ✔ E+V

graph isomorphism 2c V log V

74

You might also like