Document

Chapter 13 (Lafore’s Book) – Part 2
Graphs
Hwajung Lee

Example
C
I
E
F
A
B
J
H
G
D
DAG can have one or more topological orders.
 (ex) I B D G C E F J A H or C E G A I B F J D H


Definition
 Topological sort or topological ordering of a
directed acyclic graph (DAG) is a linear ordering of
its nodes in which each node comes before all
nodes to which it has outbound edges. Every DAG
has one or more topological sorts.
void topsort( ) throws CycleFound {
Queue q;
int counter = 0;
Vertex v,w;
q = new Queue();
for each vertex v
if (indegree == 0)
q.enqueue(v);
while (!q.empty()) {
v = q.dequeue();
v.topNum = ++counter;
for each w adjacent to v
if (--w.indegree==0)
q.enqueue(w);
}
if (counter != NUM_VERTICES)
throw new CycleFound();
}
Initialize Q with vertices
of indegree 0
Decrement indegrees of
vertices w, if 0 then
enqueue
Vertices will remain unenumerated if a cycle
exists
Queue
I
C
G
E
B
D
A
F
J
H
C
I
Load Q with initial v
with indegree == 0
E
F
A
B
J
H
G
D
Output
I
C
G
B
E
D
A
F
J
H

Source Code: topo.java

Cf. Connectivity in a non-directed graph can be
easily checked by using a depth-first or
bread-first search. That is, if you can reach all
the vertices from a randomly selected vertex
using one of the search, the non-directed
graph is connected.

However, in a directed graph, you can not check a connectivity
with a dfs or a bfs by starting from a randomly selected vertex.
It is a reachability test from a vertex to another vertex.
B
A
D
C

E
Shall we start the search on each vertex in turn and see if we
can reach all the vertices?
 Not efficient.  Whrshall’s algorithm



Warshall’s algorithm systematically modifies
a graph’s adjacency matrix.
The graph represented by the revised
adjacency matrix is called the transitive
closure of the original graph.
Idea:
 If you can get from vertex L to vertex M, and you
can get from M to N, then you can get from L to
N.
A
A
B
C
D
E
B
C
D
E
1
1
1
1
1
1
A
A
B
C
D
E
B
C
D
E
1
1
1
1
1
1
1
B
Row A: 1 is added at (B, C)
A
Row B, C, D: No update
D
Row E: 1 is added at (D, C)
E
 After update it, a dsf or bsf can be used. C