Week11 - Graphs
Week11 - Graphs
CS2002
Graphs
Graphs
(ref chapter16 of textbook)
• A graph G = (V,E) is composed of:
V: set of vertices
E: set of edges connecting the vertices in V
• An edge e = (u,v) is a pair of vertices
• Example:
a b V= {a,b,c,d,e}
E= {(a,b),(a,c),
c (a,d),
(b,e),(c,d),(c,e),
(d,e)}
d e
Applications
CS210
• electronic circuits
JFK
LAX STL
HNL
DFW
FTL
Terminology:
Adjacent and Incident
• If (v0, v1) is an edge in an undirected
graph,
– v0 and v1 are adjacent
– The edge (v0, v1) is incident on vertices v0
and v1
• If <v0, v1> is an edge in a directed graph
– v0 is adjacent to v1, and v1 is adjacent from v0
– The edge <v0, v1> is incident on v0 and v1
Terminology:
Degree of a Vertex
The degree of a vertex is the number of
edges incident to that vertex
For directed graph,
the in-degree of a vertex v is the number of
edges
that have v as the head
the out-degree of a vertex v is the number of
edges
that have v as the tail
if di is the degree of a vertex i in a graph G
with nn vertices
1 and e edges, the number of
Why? Since adjacent vertices each
edges
e ( 0
is
i
d )/ 2 count the adjoining edge, it will be
counted twice
Examples
0
3 2
0 1 2
3 3
3 1 2 3 3 4 5 6
1 1 1 1
3G1 G2
3
0 in:1, out: 1
directed graph
in-degree
out-degree 1 in: 1, out: 2
2 in: 1, out: 0
G3
Terminology:
Path
• path: sequence of
3 2
vertices v1,v2,. . .vk such
that consecutive vertices vi
3
and vi+1 are adjacent.
3 3
a b a b
c c
d e d e
abedc bedc
7
More Terminology
• simple path: no repeated vertices
a b
bec
c
d e
• cycle: simple path, except that the last vertex is the same as the first
vertex
a b
acda
c
d e
Even More Terminology
•connected graph: any two vertices are connected by some path
n
5
m (5
More Connectivity
n = #vertices n 5
m = #edges m 4
• For a tree m = n - 1
If m < n - 1, G is
not connected
n 5
m 3
Oriented (Directed) Graph
tail head
Graph ADT
Graph Representations
Adjacency Matrix
Adjacency Lists
Adjacency Matrix
G4
Merits of Adjacency Matrix
#define MAX_VERTICES 50
class node {
int vertex;
node *link;
};
node *node_pointer;
node_pointer graph[MAX_VERTICES];
int n=0; /* vertices currently in use */
0 0 4
2 1 5
1 2 3 6
3 7
0 1 2 3 0 1 2
1 0 2 3 1 0 3
2 0 1 3 2 0 3
3 0 1 2 3 1 2
G1 0 4 5
5 4 6
0 1 6 5 7
1 0 2 1
7 6
2
G3 G4
2
An undirected graph with n vertices and e edges ==> n head nodes and 2e list nodes
Some Operations
degree of a vertex in an undirected graph
–# of nodes in adjacency list
# of edges in a graph
–determined in O(n+e)
out-degree of a vertex in a directed graph
–# of nodes in its adjacency list
in-degree of a vertex in a directed graph
–traverse the whole data structure
Graph Traversal
depthfirstSearch(v)
{
Label vertex v as reached
for (each unreached vertex u adjacent from v)
depthfirstSearch(u)
}
DFS
F B A start
DFS Process E
G D C
destination
A B D C D
Initial call to BFS on A Dequeue A Dequeue B Dequeue C
Add A to queue Add B Add C, D Nothing to add
rear front