The Graph ADT
!
A graph is a simple mathematical object, useful in many
different computational contexts
An ordered pair G = (V, E) with:
V: a set of vertices (elementary graph nodes)
2. E: a set of edges, E ⊆ V ×V (pairs of vertices)
!
1.
E = { (v, w) | There is an edge from v to w }
Class #37:
Graphs and
Basic Graph Algorithms
Software Design III (CS 340): M. Allen, 25 Apr. 16
!
Each edge (and the graph itself) is directed, since we have a
fixed ordering of the node-pairs (v, w)
!
Undirected graphs can be defined the same way, so long as we
have a symmetry condition for edge-pairs:
(v, w) ∈ E ⇔ (w, v) ∈ E
Monday, 25 Apr. 2016"
Example: A Simple Directed Graph
0
(0,3)
(1,4)
2
3
(3,5)
5
For any vertex (node) v ∈ V, the degree of v is the
number of edges from v to any other vertex
!
The in-degree of v is the number of edges to v from any
other vertex
!
A path in G is a sequence of (n ≥ 1) edges from some
source vertex s to some other target vertex t
4
(2,5)
(3,2)
!
1
(0,2)
(1,3)
2"
Graph Terminology
Edges
(0,1)
Software Design III (CS 340)"
6
!
(3,6)
!
(4,3)
A cycle in G is a path from some vertex v back to v
!
(4,6)
The length of the path is its number of edges
A graph is acyclic if no cycles exist
(6,5)
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
3"
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
4"
1
Example: A Simple Acyclic Graph
degree: 3
in-degree: 0
degree: 1
in-degree: 2
Using Graphs
!
0
1
2
3
!
A graph is a simple, abstract data structure
As such, it is suitable for representing any “points of
interest” and basic binary relationships between them
!
4
!
!
degree: 0
in-degree: 3
5
A path
from 0 to 5
6
!
!
!
Another path
from 0 to 5
!
!
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
5"
Monday, 25 Apr. 2016"
CS120
CS364
CS464
CS227
CS351
CS341
CS220
CS449
CS402
CS451
CS410
CS455
CS452
CS340
0
1
3
4
CS453
CS270
CS431
5
CS471
CS370
CS454
CS353
CS446
CS441
CS470
Monday, 25 Apr. 2016"
An (N × N) binary array marking each possible edge (1/0)
2
CS352
CS442
CS456
CS443
Software Design III (CS 340)"
6"
One possibility: an adjacency matrix.
CS421
CS225
CS224
!
!
CS342
Software Design III (CS 340)"
Representing a Graph
Example: Computer Science Prerequisites
CS202
Industrial processes and ordering relationships.
Code blocks and simultaneous operation.
Individual people and personal compatibility (or lack of same).
Sports teams and common games between them.
States of a board game and moves between them.
Cities in a country and roads between them.
Locations in a maze and possible moves between them.
…
7"
Monday, 25 Apr. 2016"
6
0
1
2
3
4
5
6
0
0
1
1
1
0
0
0
1
0
0
0
1
1
0
0
2
0
0
0
0
0
1
0
3
0
0
1
0
0
1
1
4
0
0
0
1
0
0
1
5
0
0
0
0
0
0
0
6
0
0
0
0
0
1
0
Software Design III (CS 340)"
8"
2
Representing a Graph
Topologically Sorting Acyclic Graphs
!
With an adjacency matrix, the size required to store a graph
consisting of N vertices is always Θ(N × N) = Θ(N2)
!
When a graph is dense—meaning that almost every vertex is
connected to every other—this is fine, since the upper limit on the
number of edges is already close to that:
!
|E| = N × (N – 1) = Θ(N2)
When a graph is sparse—with relatively few edges—the adjacency
matrix can waste a lot of space, however
In such cases, an adjacency list is generally preferable:
!
!
!
!
!
!
A list of N vertices
For each vertex, a list of its out-edges
Total space: Θ(|V| + |E |)
May mean slower access times to the list, but for large graphs, this can
be worth trading off over huge memory burdens
!
!
!
When a graph has no cycles, its nodes can be put into a
topological ordering:
v0, v1, v2, …, vN
In such an ordering, if there is a path from vi to vj in the graph,
then vj must occur later in the ordering sequence
If the graph is cyclic, then no such order is possible, since
there will always be at least two nodes in the cycle, and they
can’t both come later than each other
Such an ordering gives us a way of moving through the graph
in some permissible order :
!
!
!
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
9"
Topologically Sorting Acyclic Graphs
1.
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
10"
Pseudocode for Topological Sort
To find a topological ordering we rely upon the fact that every acyclic graph
must have at least one vertex v with in-degree = 0
!
A proper sequence of moves in a game
A proper sequence of courses with prerequisites
…
Proof: Let P = v1→v2→⋯→vk be a longest path in graph G
(At least one path must be longer than the others)
Input: Graph G = (V, E ) !!
Output: Ordered list of vertices!
2.
Now, either v1 has in-degree 0, or there exists some edge (vj → v1)
Initialize empty vertex list, L
3.
If the vertex vj doesn’t occur in path P, then the path vj→v1→ ⋯ →vk is
longer than P, which is not possible by the definition of a longest path
4.
However, if vj does occur in path P, then graph G is cyclical. Thus, if G is
acyclic, v1 must have in-degree 0
!
Thus, we can use any such v as the first element in the ordering: since it
has 0 in-degree, no matter how we order the rest of the nodes later, none
of them will have any edge back to v
We can then remove v from the graph and repeat the process on the rest
of the vertices until we have put them all in order
While length of L < |V|:!
Find vertex v with in-degree = 0:!
if no such v exists: ERROR( “CYCLE” )!
else add v to end of list L!
Delete v and all adjacent edges from G!
!
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
11"
Return list L
Monday, 25 Apr. 2016"
!
Software Design III (CS 340)"
12"
3
Performing Topological Sort
/"
/"
0
/
/
0
/
3
1
4
4
/
5
6
3
2
6
private LinkedList<Vertex> topoSortVertices() !
{
!
LinkedList<Vertex> sort = new LinkedList<>();
LinkedList<Vertex> q = new LinkedList<>();
In-degree of vertices
1
/
2
Coding Topological Sort
5
d
d
d
d
0
0
1
1
0
2
2
1
1
1
3
3
2
1
0
d
d
d
for ( Vertex v : vertices )
if ( v.inDegree == 0 )
q.add( v );
4
1
1
0
5
3
3
3
3
2
1
6
2
2
2
1
0
0
0
return sort;
!
!
!
!
while ( ! q.isEmpty() )
!
{
!
Vertex v = q.remove();
sort.add( v );
!
for ( Vertex next : v.adjacent )
{
!
next.inDegree--;
if ( next.inDegree == 0 )
q.add( next );
!
}
!
} !
0
!
!
!
!
!
Note: the actual method is
somewhat more complex,
due! to the need to check
for cycles, re-set adjusted
in-degree values, etc. (See
sample code.)
}
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
13"
Shortest Paths in Elementary Graphs
!
!
!
LinkedList<Vertex> queue = new LinkedList<>();
HashMap<Vertex, Vertex> prev = new HashMap<>();
queue.add( source );
!
prev.put( source, source );
}
Software Design III (CS 340)"
14"
private LinkedList<Vertex> shortestPathVertices( int s, int t ) {!
Vertex source = vertices.get( s );
!
Vertex target = vertices.get( t );
!
This works by simply tracking the vertices we can get to in one
step from the start, then those we can get to in two steps, then
three steps, …
The shortest path to the target will be the first one that is
found in the search process
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
Shortest Paths in Simple Graphs
For simple graphs, all edges are the same “quality”, and
the shortest path is the one with least number of edges
Starting with any source vertex, and looking for some
target, we can find the shortest path between them (if
one exists) using breadth-first search
!
Monday, 25 Apr. 2016"
15"
!
!
!
Note: in order to be able to
return the actual path once
we have found it, we keep a
map from vertices to their
!
previous neighbor
in the path.
while ( ! queue.isEmpty() ) {
!
Vertex v = queue.removeFirst();
for ( Vertex next : v.adjacent ) {
!
if ( ! prev.containsKey( next ) )
!
The backtrack()
method
{
!
prev.put( next, v );
! will return that path, given the
map, and the two end-nodes.
queue.add( next );
!
}
!
if ( next.equals( target ) )!
return backtrack( prev, target, source );
!
}
!
}
!
return new LinkedList<Vertex>();
!
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
16"
4
This Week and Next Week
!
Reading: Chapter 9 (Graphs)
!
Meetings: regular pattern
!
Lab day Friday
!
Last Homework Assignment: due Friday, 06 May
!
Office Hours: Wing 210
!
!
Tuesday & Thursday: 10:00–11:30 AM
Tuesday & Thursday: 4:00–5:30 PM
Monday, 25 Apr. 2016"
Software Design III (CS 340)"
17"
5
© Copyright 2026 Paperzz