Introduction To Graphs
Introduction To Graphs
Ma/CS 6a
Class 6: Introduction to Graphs
By Adam Sheffer
1
10/8/2015
Graphs
Undirected Directed
graph graph
𝑎 𝑏 𝑎 𝑏
Edge
Vertex
2
10/8/2015
Graph Representation
We write 𝐺 = 𝑉, 𝐸 . That is, the graph 𝐺
has vertex set 𝑉 and edge set 𝐸.
𝑐 𝑐
𝑎 𝑑
𝑒 𝑏 𝑎 𝑏
𝑑 𝑒
3
10/8/2015
𝑏 𝑎
Path Cycle
between 𝑎 through 𝑎
and 𝑏.
A cycle is a path that starts and ends in the same
vertex.
4
10/8/2015
Connected? Connected?
deg(𝑎) = 2 deg(𝑎) = 1
𝑎 𝑎
5
10/8/2015
Simple Graphs
An edge is a loop if both of its endpoints
are the same vertex.
Two edges are parallel if they are
between the same pair of vertices.
A graph is simple if it contains no loops
and no parallel edges.
For now, we only consider simple graphs.
Parallel
A loop edges
Warm-up Exercise
Prove. In any graph, the sum of the
degrees of the vertices is even.
6
10/8/2015
Proof
Assume for contradiction that a longest path 𝑃
is of length 𝑐 < 𝑑.
Consider a vertex 𝑣 which is an endpoint of 𝑃.
Since deg 𝑣 ≥ 𝑑 ≥ 𝑐 + 1, it must be
connected to at least one vertex 𝑢 ∉ 𝑃.
By adding the edge 𝑣, 𝑢 to 𝑃, we obtain a
longer path, contradicting the maximality of 𝑃.
7
10/8/2015
𝑑+1
Connectivity Problem
Prove. The vertices of a connected graph
𝐺 can always be ordered as 𝑣1 , 𝑣2 , … , 𝑣𝑛
such that for every 1 < 𝑖 ≤ 𝑛, if we
remove 𝑣𝑖 , 𝑣𝑖+1 , … , 𝑣𝑛 and the edges
adjacent to these vertices, 𝐺 remains
connected. 𝑣4
𝑣3
𝑣1 𝑣2
𝑣5
8
10/8/2015
Proof
Pick any vertex as 𝑣1 .
Pick a vertex that is connected to 𝑣1 in 𝐺
and set it as 𝑣2 .
Pick a vertex that is connected either to
𝑣1 or to 𝑣2 in 𝐺 and set it as 𝑣3 .
…
Back to Bacon
We wish to build a graph for the problem.
What are the vertices of the graph?
◦ A vertex for each actor.
When is there an edge between two
vertices?
◦ When the corresponding actors played in a
common movie.
Is the graph directed?
◦ No.
9
10/8/2015
Example
Bacon Numbers
The Bacon number of an actor is the
minimum number of steps required to
connect him/her to Kevin Bacon.
Example. By the picture below:
◦ Christopher Walken’s Bacon number is 2.
◦ Keanu Reeves’ Bacon number is 4.
10
10/8/2015
11
10/8/2015
Rooted Trees
A rooted tree is a tree with a special
vertex – the root – that is singled out.
We draw the tree with the root on top,
and the edges “grow downwards”.
A vertex 𝑣 is the parent of a vertex 𝑢 if
there is an edge 𝑢, 𝑣 and 𝑣 is above 𝑢.
◦ Each vertex, except for the root,
has a unique parent. 𝑠
𝑡
12
10/8/2015
BFS Output
𝑠
𝑠 𝑎 𝑏
𝑐 𝑎
𝑐 𝑑 𝑒 𝑑 𝑏
Answer. No!
𝑠 𝑎
𝑠 𝑠
𝑏 𝑐 𝑏 𝑎 𝑏 𝑎
𝑐 𝑐
13
10/8/2015
BFS: Colors
We call the vertex 𝑠 that we start from the
root of the tree.
BFS scans the graph starting from the root.
During the scan, every vertex has a color:
◦ Vertices that the algorithm did not visit yet are
colored white.
◦ Vertices that the algorithm did visit, but is not
yet done with are colored gray.
◦ Vertices that the algorithm is done with are
colored black.
14
10/8/2015
15
10/8/2015
s s s s
f b f b f b f b
e e e e
c c c c
d d d d
16
10/8/2015
The End
17