Rochester Institute of Technology
RIT Scholar Works
Theses
Thesis/Dissertation Collections
9-11-1991
Optimization algorithms for shortest path analysis
Susan M. Hojnacki
Follow this and additional works at:
http://scholarworks.rit.edu/theses
This Thesis is brought to you for free and open access by the Thesis/Dissertation Collections at RIT Scholar Works. It has been accepted for inclusion
in Theses by an authorized administrator of RIT Scholar Works. For more information, please contact
Recommended Citation
TABLE OF
CONTENTS
TABLE OF
FIGURES
iii
TABLE OF
TABLES
iv
ABSTRACT
v1
Networks
andGraph
Theory
1
1.1
Introduction
andBackground
1
1.2
Classification
ofDigraphs
5
2
Network Matrices
andData Structures
9
2.1
Matrix
Representations
ofNetworks
9
2.2
Other
Network
Representations
-Data Structures
13
2.3
Transitive
Closure
16
3
Description
ofAlgorithms
18
3.1
Dijkstra's
Shortest Path Algorithm
18
3.2
Bellman-Ford Shortest Path
Algorithm
23
3.3
Floyd-Warshall Algorithm
26
4
Analysis
andResults
30
4.1
Dijkstra's
Shortest Path Algorithm
31
4.2
Bellman-Ford Shortest Path
Algorithm
34
4.3
Floyd-Warshall
Algorithm
35
4.4
Time
Trials
37
4.4.1
Sparse Network
37
4.4.2
Complete Network
38
REFERENCES
44
APPENDIX A:
PROGRAM LISTINGS
46
algdl.c
46
algd2.c
50
algd3.c
55
algd4.c
59
algbfl.c
63
algbf2.c
68
algfw.c
73
spath.h
76
APPENDIX
B:
Program Instructions
andExamples
77
Example #1:
All Arcs Have Positive Weights
77
Example #2:
Some Arcs
With Negative Weights
80
Example #3:
A
Network With A Negative Cycle
82
Dijkstra's Shortest Path Algorithm
83
Instructions for
Running
algdl.c83
Instructions
for
Running
algd2.c87
Instructions
for
Running
algd3.c91
Instructions
for
Running
algd4.c94
Bellman-Ford Algorithm
97
Instructions
for
Running
algbfl.c97
Instructions
for
Running
algbf2.c102
Floyd-Warshall Algorithm
115
Instructions
for
Running
algfw.c115
APPENDIX C:
Evaluation
ofSimulation Software
127
TABLE
OF
FIGURES
Figure 1.1
Graph
Representation
of aNetwork
2
Figure
1.2a
Example
of a selfloop
3
Figure 1.2b
Example
of parallel arcs3
Figure 1.2c
Example
of a cycle3
Figure
1.3
Example
of aReflexive Digraph
5
Figure
1.4
Example
of aSymmetric Digraph
5
Figure 1.5
Example
of aTransitive Digraph
6
Figure 1.6
Example
of anIrreflexive
Digraph
6
Figure 1.7
Example
of anAsymmetric Digraph
7
Figure 1.8
Example
of anAntisymmetric
Digraph
7
Figure 1.9
Example
ofanEquivalence
Digraph
8
Figure 2.1
Node-Arc Incidence Matrix
10
Figure 2.2
Digraph
With Weights
11
Figure
2.3
Weight Matrix
11
Figure
2.4
Adjacency
Matrix
12
Figure
2.5
Linked
Adjacency
List Representation
14
Figure
2.6
Forward Star Representation
16
Figure
B.l
Digraph
for
Example #1
78
Figure
B.2
Digraph
for
Example
#2
81
TABLE
OF TABLES
Table 4-1
Comparison
ofDijkstra
andBellman-Ford
Algorithms
for
aSparse
Network
37
Table 4-2 Comparison
ofDijkstra, Bellman-Ford,
andFloyd-Warshall
Algorithms
for
aSparse
Network
38
Table 4-3
Comparison
ofDijkstra
andBellman-Ford Algorithms
for
aComplete
Network
39
Table 4-4 Comparison
ofDijkstra, Bellman-Ford,
andFloyd-Warshall
Algorithms
ABSTRACT
Discrete
optimization algorithms existfor
analysis of network optimization offlow
problems.
Computer
programs writtenfrom
these
algorithms canbe
usedfor local
areanetwork analysis of point-to-point computer
networks, transportation
networks,
resourceallocation,
distribution,
and production scheduling.One
aspect of a networkthat
canbe
optimizedusing
discrete
optimization algorithmsis
the
length
ofthe
paththat
data
will
take
whentraveling
through the
network.One
nodein the
network signifiesthe
source node and a second node
is
the
sink ordestination.
The
objectis
to
find
the
shortest path
between
the two
nodes.The
definition
of shortest pathdepends
onthe
quantity
analyzedin
the
network."Shortest
path"canrepresent
the
fastest
path,
mostcost-efficientpath,
mostfuel-efficient
path,
etc.Also,
different
levels
of computationmay be
required.It
may
be
necessary
to
find
the
shortest pathbetween
two
nodesin
anetwork,
the
shortest pathbetween
asource node and all other nodes
in
anetwork,
orthe
shortest pathbetween
all pairs ofnodes
in
a network.The
complexity, performance,
and results ofdifferent
optimization methods canbe
compared
using
a series ofnetwork models.A
comparisonofthe
algorithmsresearchedChapter
1
Networks
and
Graph
Theory
1.1
Introduction
and
Background
A
network consists of nodes(vertices)
and arcs(edges).
The
arcs represent means oftransport
in
the
network andthe
nodes arelocations
connectedby
the
arcs.Some
examples of networks
include:
alocal
areanetwork,
atelephone
communicationsnetwork,
andatransportation
network madeup
of roads andhighways.
Networks
canbe
modeled and analyzedusing
graphs and graphtheory.
This
chapter presents someof
the
basics
of graphtheory
necessary
to
understandthe
discrete
optimizationalgorithms
that
willbe
presented.The
arcsin
a network canhave
adirection
associated withthem,
in
which casethey
arecalled
directed
arcs.A
weight orcapacity
is
associatedwith each arc.The
weight canbe
represented as alower
orupperbound.
Distance,
cost, penalties,
time,
orany
otherquantity
to
be
minimized canbe
usedfor
arcweightsin
anetwork.Some
networkswillhave
negative arcweights.Negative
arc weightscan representcostsin
anetwork,
whilepositive ones can represent profits.
A
networkcanbe
described
by
alabeled
drawing
or amatrix.A
labeled
drawing,
alsocalled a
graph,
contains circles andlines
segments.The
circles represent nodesin
the
then the
line
segmentshave
directional
arrows
andthe
graphis
called adirected
graph,
or
digraph.
Figure 1.1 is
adigraph
with six nodes and nine arcs.The
nodes arelabeled
from
0
to
5,
andthe
arcs arelabeled from
0
to
8.
Figure 1.1
Graph
Representation
of aNetwork
A
directed
arcfrom
nodena
to
noden2 is
representedby
the
ordered pair(n^nj).
Arc
number
1 in Figure 1.1
canbe
representedby
the
ordered pair(0,5).
Arcs
can alsobe
labeled
with numbers orletters.
A
graphin
which none ofthe
arcshave
adirection
associated with
them
is
called an undirected graph.The
number ofarcsleaving
a nodeis
calledthe
out-degree or out-valence.The
numberofarcs
entering
a nodeis
calledthe
in-degree
orin-valence.
The
sum of allin-degrees
A
selfloop
is
an arc whose source anddestination
nodes arethe
same.In Figure
1.2a,
node
1
has
a selfloop.
Parallel
arcs occur whentwo
arcshave
the
samedirection
andalso
have
the
same source anddestination
node.In
Figure
1.2b,
arcs1
and2
areparallelarcs.
A
paththrough
a networkis
a series of successive arcsin
which no nodeis
repeated.
A cycle,
ordirected
circuit, is
a paththrough
adirected
graphthat
starts and
ends at
the
same node.A
negative cycleis
a cyclein
whichthe
sum ofthe
arcweightsis
negative.A
networkthat
does
not containany
cyclesis
called acyclic.In
Figure
1.2c,
the
sequence of arcs(1, 2,
4)
is
a cycle.(a)
(b)
(c)
Figure 1.2
Example
of(a)
a selfloop,
(b)
parallelarcs,
and(c)
a cycleA
simpledirected
graphis
a graphthat
does
not containany
selfloops
or parallel arcs.All
ofthe
algorithms researched operate onsimpledirected
graphs only.A
graphthat
is
not simple canbe
made simpleby
replacing
each set of parallel arcs withthe
shortestarc of
the
set(arc
withthe
smallest weight).Self
loops
canbe
removedfrom
the
graphreplacing
each undirected arc withtwo
directed
arcs(in
oppositedirections)
with equalweights.
However,
if
an undirected archas
a negative weight associated withit,
replacing
the
undirected arc withtwo
directed
arcs will create a negative cycle.The
shortest path problemis
an optimization problem.An
optimization problemmay
have many
solutions,
but
only
one solution(or
a set ofsolutions) is
the
best
solution.This
solutionis
called optimal(although
there
may be
morethan
one optimal solution).The
shortest pathproblemis
defined
asfinding
the
minimum weight pathfrom
a sourcenode
to
adestination
node,
for any
given node pairin
the
network,
based
on arcweights.
The
shortest pathdoes
not containany
repeated nodes.There
canbe
morethan
one optimal solutionto the
shortest path problemif
there is
morethan
one pathfrom
sourceto
destination
withthe
same irunimum path weight.There
arethree
cases ofshortest path problems:1. All
arc weights are non-negative.2. Some
arc weights arenegative,
but
there
are no negative cycles.3. There is
atleast
one negative cyclein
the
network.The
third
case cannotbe
solved.However,
there
exist algorithmsthat
canfind
the
1.2
Classification
of
Digraphs
1.
simpleThere
are no selfloops
or parallel arcs.The digraph
in Figure 1.1
is
a simpledigraph.
2.
reflexive3.
symmetricEvery
nodein
the
networkhas
a selfloop.
Figure 1.3
Example
of aReflexive Digraph
For
every
arcin
onedirection between
two
nodes,
there
is
also anarc
in
the
oppositedirection
between
the
sametwo
nodes.Figure 1.4
4.
transitive
If
there
is
an arcfrom
nodea{
to
nodea,
andan arcfrom
nodeaf
to
node
aw
*k/then there
is
an arcfrom
node a=to
nodeaw
Figure 1.5
Example
ofaTransitive
Digraph
5. irreflexive
There
are no selfloops in
the
network.Figure 1.6
6.
asymmetricThere is
at most onedirected
arcbetween
a pair ofnodes,
notwo
nodes
have
arcsin
both directions.
Self
loops
are not permitted.Figure 1.7
Example
of anAsymmetric Digraph
7.
antisymmetricThere is
at most onedirected
arcbetween
a pair of nodes.Figure
1.8
8.
equivalenceA digraph
that
is
reflexive, symmetric,
andtransitive.
<b
Figure 1.9
Chapter
2
Network
Matrices
and
Data Structures
2.1
Matrix
Representations
of
Networks
One
way
to
model a networkis
with a matrix.This
representationis ideal
for
performing
calculations on networkinformation.
Given
a network with n nodesnumbered
0
to
n -1,
and m arcsnumbered
0
to
m -1,
the
first
matrixdepiction
examined can
be defined
as:+1
if
arcj
is
directed
away
from
nodei
au
={
-1
if
arcj
is
directed
towards
nodei
0
if
arcdoes
not exist'j
for
i
=0,1,...,
tj-1j
=0,1,...,
m-1where
a^
is
the
elementin
the
ithrow andj* column of matrixA.
The
resulting
matrixwill
be
i
rowsby
/
columns,
i
corresponding
to nodes,
andj
corresponding
to
arcs.This
matrix
is
calledthe
node-arcincidence
matrix1,
also calledthe
vertex-arcincidence
matrix2.1
Bazaraa,
M.
andJ.
Jarvis,
Linear
Programming
andNetwork
Flows,
John
Wiley
&
Sons,
New
York, 1977,
p
407.
2
A
node-arcincidence
matrixfor
the
digraph
in
Figure
1.1 is
shownbelow.
ARCS
NODES
0
1
1
1
2
0
3
0
4
0
5
0
6
0
7
0
8
0
-1
0
1
1
0
0
0
0
0
0
0
-10
1
1
0
-10
0
0
0
0
-10
-10
0
0
0
0
0
0
-11
0
-10
-10
-10
0
0
1
1
Figure 2.1
Node-
Arc Incidence Matrix
It
canbe
seenthat
eachcolumn ofthe
node-arcincidence
matrix willhave
exactly
two
non-zero
entries,
a single+1
entry,
and a single -1entry, the
reasonbeing
that
each arccan enter
only
one node and canleave only
one node.Another
matrix representation of a networkis
the
weight matrix representation.In
this
representation,
a networkwith n nodes couldbe
representedby
annby
nmatrix,
calledW,
defined by:
wi;
weight
if
arc(ij)
existsoo
if
arc(ij)
does
not existfor i
=0,1
n-1j
=Figure 2.2
showsthe
results ofadding arbitrary
weights(for
purpose ofexample)
to the
digraph
in Figure 1.1.
The
weights aredisplayed
in
boxes,
nextto
the
arcthey
describe.
Figure 2.2
Digraph
With Weights
The
entries onthe
diagonal
ofthe
matrix are setto
0,
making
the
weight matrixirreflexive.
Parallel
arcs and selfloops
cannotbe
representedin
a weight matrix.The
weight matrix
for
the
digraph in Figure 2.2 is
asfollows:
0
14
oo oo oo7
00
0
18
0 0025
oo oo
0
9
11
00 00 oo
0
00 oo00 oo oo
15
0
oo oo
33
oo20
0
Figure
2.3
A
third
matrix representation of adigraph
is the
adjacency
matrix representation.This
representation
is
similarto the
weightmatrix,
but
instead
ofdescribing
weightsin
the
matrix,
an arc's presencebetween
two
nodesis
represented.Parallel
arcs cannotbe
represented with an
adjacency
matrix.The
adjacency
matrix,
X
=[xJ,
whereXH
=1
if
there
is
an arcdirected from
nodei
to
nodej
0
if
an arcdoes
not existbetween
nodei
and nodej
for i
=0,1,...,
n-1j
=0,1,...,
tj-1Self
loops
canbe
representedin
anadjacency
matrixby
a1
atxti
(meaning
nodei has
a self
loop). There
aresix nodesin
Figure
2.2,
sothe
adjacency
matrixfor
Figure 2.2
willbe
a6
by
6
matrix.The
adjacency
matrixfor
Figure 2.2 is
asfollows:
0
10
0
0
1
0
0
10
0
1
0
0
0
110
0
0
0
0
0
0
0
0
0
10
0
0
0
10
10
Figure 2.4
2.2
Other Network
Representations
-Data Structures
Let
m representthe
number of arcsin
anetwork,
andlet
n representthe
number ofnodes.
A
network wherethe
number of m arcsis
muchless
than
n *(n
-1)
(the
total
of all possible
edges)
is
called a sparse network.Using
a matrix representationfor
asparse
directed
network would notbe
efficientbecause
it
wouldtake
up
n2words of
storage,
few
of which wouldbe
usedto
store entriescorresponding
to
existing
arcs.A
morepractical
way
to
represent a sparse network wouldbe
to
use adata
structurethat
lists
the
arcs ofthe
network.One
such representationis
calledthe
adjacency
list
orlist
of
edges.This
representation consists ofthree
one-dimensionalarrays,
originstoresthe
originating
node ofthe arc, target
storesthe
destination
node ofthe arc,
and weightstores
the
length
ofthe
arc.Arq
starts atorigin^,
ends attarget;,
andhas
a weight ofweightj.
The
amount of computerstoragerequiredfor
this
networkrepresentationis
3m
words.
For
example, the
networkin Figure
2.2 is
a sparse network.There
are9
arcs and6
nodes.
The
following
arraysdescribe
the
networkdisplayed
in Figure
2.2:
origin =
(0, 0,
1, 1, 2, 2, 4, 5,
5)
target
=(1,
5, 2, 5, 3, 4, 3, 2,
4)
weight =
(14,
7, 18, 25, 9, 11, 15, 33,
20)
The
amount ofstorage requiredis
27
words,
comparedto
the
matrix representationfor
this
network which would require36
words of storage.The
storage savingscanbe large
A
seconddata
structurefor
network representationis
calledthe
linked
adjacency
list?.
There
are nlinked
lists,
onefor
each nodein
the
network.All
arcsradiating from
the
ith
node arelinked
together.
Each
elementin
the
linked
list defines
an arcin
the
network and
is
a structurecontaining
the
node number ofthe target
ofthe arc,
andthe
weight of
that
arc.This
type
ofdata
structure requires n +3m
words ofstorage.The
linked adjacency list for
the
networkin Figure 2.2 is
shownin Figure 2.5.
The
amount of storage required
for
this
networkis 33
words.o
l
2
3
4
5
pointer
J
jt-f
J
j*
4*\
1 14 N/ 5 7 NIL
2 18 N * 25 NIL
)
\
\
3 9 < 11 NIL
) '
NIL
\
3 15 NIL ?
\ 2 33 \ 4 20 NIL
)
Figure 2.5
Linked
Adjacency
List Representation
Another
network representationis
calledthe
forward
star4.This
data
structure consistsof
three
arrays.The
first array
contains a pointer orindex
for
each nodein
the
network.This
pointer pointsto
alocation
in the
second andthird
arrays.The
second andthird
arrays
describe
the
arcs.The
secondarray
containsthe
arcs'target
nodenumber,
andthe
third
array
containsthe
weight ofthat
arc.The information in
the
second andthird
arrays
for
the
arcs ofthe
ith
node are stored sequentially.The
forward
star of nodei
consists of all
the
arcsradiating from
nodei.
The
amount of storage requiredis
n +1
+
2m
words.For
example, the
forward
stardata
structure ofthe
network shownin Figure 2.2 is
displayed
in Figure 2.6.
Node 6
does
not exist.Its
pointer pointsto the
next availableslot
in
the target
and weight arrays.This is
necessary
in
orderto
computethe
first
andlast
index into
the target
andweight arraysfor
node5. The
amount of storage requiredfor
this
networkis
25
words.pointer target weight
0
l 14
?
1
5 7
2
U
2 18
3 5 25
3 9
1 7
4 11
6 9
i=s
3 15v
2 33
;
4 20
Figure 2.6
Forward
Star
Representation
The
linked
adjacency
list
andthe
forward
stardata
structures are convenientfor
programming
purposes sincethey
implicitly
define
the
originating
node of each arc.The
linked adjacency list
is
especially
suitablefor
applications where nodes areto
be
addedand
deleted from
the
network.2.3
Transitive
Closure5G is
an n-nodedigraph
andM
is
the
weight matrixfor
G.
To
computethe transitive
closure of graph
G,
construct another n-nodedigraph
by
adding
arcsto
G
asfollows:
add an arc
(i,j)
directed from
nodei
to
nodej
if
andonly
if there is
adirected
path(of
5
any length
2,3,...,
n-1) from
i
to
j
in G.
Examine
all arcsincident
to
a nodebefore
exarnining
the
next node.While
examining
anode, the
arcsincident
to the
node canbe
chosen
in
any
order.The
resulting digraph
is
calledthe transitive
closure ofG.
The
weight
matrix,
M,
describing
G is transformed
by
overwriting
directly
onM
(the
intermediate
matrices are not saved).66
Chapter 3
Description
of
Algorithms
Similar
notation willbe
usedto
describe
each ofthe
algorithms studied.The
total
number of nodes
in the
networkis
equalto
n.The
nodes are numberedfrom
0
to
n-1.
The
number of arcsin
the
networkis
equalto
m andthey
are numberedfrom
0
to
m-
1.
In
aweightmatrix, the
weightof a non-existentarcis
representedby
INFINITY.
The
source nodeis
called s andthe
destination
nodeis
calledd.
Also,
for any
realnumber
r,
r +INFESfrTY
=INFINITY.
3.1
Dijkstra's Shortest Path Algorithm
An
algorithm which computesthe
shortest pathfrom
one nodein
a networkto
another node
in
anetworkis Dijkstra's Shortest Path Algorithm. This
algorithmis
considered a"greedy
algorithm"
because
it
always picksthe
choicethat
looks
the
best
atthe
moment.Greedy
algorithmsdo
not always resultin
optimalsolutions,
but
this
algorithmis
anexception.7
7
Dijkstra's
algorithm uses alabel-setting
method.Each
nodein
the
networkhas
a
label,
permanent ortemporary,
and a weighted value which representsthe
distance,
cost,
or some other valueto
be
optimizedfrom
that
nodeto the
sourcenode.
If
a nodehas
been permanently
labeled,
then the
node's weighted valuerepresents
the
shortest weight(distance)
from
that
nodeto the
source node.If
anode
has
atemporary
label,
then
its' weighted value represents an upperbound
on
the
weight(distance)
between
that
node andthe
source node.For
this
algorithmto
workcorrectly,
allthe
arclengths
in
the
net mustbe
positive.
This
algorithm uses n -1 iterations
for
the
worst case(when
the
destination
nodeis
the
farthest
nodefrom
the
source node).Initialization:
Label
all nodesin
the
network withdistance
=INFINITY
(some large
numberfor
practical purposes).
Set distance
=0
for
the
source node(distance
from
the
source node
to
itself is
zero).The
source nodeis
the
only permanently
labeled
node at
this
point.Iteration:
Label
eachimmediate
successor node(i)
ofthe
source node(s)
with atemporary
label
equalto the
weight ofthe
arcfrom
sto
i.
The
node withthe
smallestsmallest weight).
Ties
canbe
broken
arbitrarily.Make
this
nodes'
label
permanent and call
it
recent.It
is
the
most recent nodeto
be
permanently
labeled,
andthe
closest nodeto the
source node.Next,
examine allthe immediate
successors of node recent and shorten
their
temporary
labels
if
the
pathfrom
the
source node
to
any
ofthem
is
shorterby
going
through
recentthan
by
notgoing
through
recent.Then,
from
allthe
temporarily
labeled
nodes,
pickthe
one withthe
smallestlabel.
Make its
label
permanentand callit
recent.Node
recentis
the
second closest node
to the
source node.Continue
looping,
decreasing
the
values ofthe
temporary
labels
when possibleby
choosing
a shorterpaththrough the
mostrecently
permanently labeled
node.Then
selectthe
node withthe
smallesttemporary
label
and makeit
permanent.Terminate
the
loop
whenthe
destination
node,
d,
gets a permanentlabel.
The
shortestpathfrom
node sto
noded
is identified
by
tracing
the
permanently
labeled
nodesbetween
node s and noded.
The
network representation usedin
this
algorithmis
a weight matrix.The C
program written
to implement this
algorithmis
called algdl.c.The
programlisting
is displayed in Appendix A.
Instructions
for running
the
program andanalyzing
the
results arein Appendix B. An
exampleis
also shownin
Appendix
The
networkis
madeto
look like
it
contains all arcs possibleby
assigning
arclengths
ofINFINITY
to
non-existent arcs.Therefore,
the time
it
takes
to
find
the
shortest path
depends
onthe
number ofnodes,
and notthe
number of arcsin
the
network.
The
time that
canbe
expectedfor
a complete networkis 0(n2).
If
the
networkis
sparse,
asit is in
most practicalapplications, the
computationtime
for
this
algorithmremainsthe same,
0(n2).
Therefore,
this
algorithmis
notefficient
for
finding
a shortest pathfrom
source nodeto
destination
nodein
asparse network when a weight matrix
is
usedto
describe
the
network.The
computation
time
for
finding
the
shortest pathin
a sparse network canbe
reduced
by
using
adifferent
matrix representation(or
data
structure).A
linked
adjacency
list
representation canbe
used.Another
way
to
shortenthe
computation
time
for
this
algorithmis in
the
iteration
phase,
instead
oflooking
at
ALL
the
temporarily
labeled
nodes(to
see which one shouldbe
permanently
labeled),
only look
atthe
nodes which are successors ofthe
mostrecently
permanently labeled
node.This
canbe done
by keeping
anarray,
0..n,
ofallthe
nodes
in
the
network,
withthe
first
mnodesin
the
array
temporarily
labeled,
andthe
nodesfrom
mto
npermanently labeled.
However,
this
modification willalgdl.c
has been
modifiedto
usethe
linked
adjacency list
structureinstead
ofthe
weight matrix representation.
The
modifiedC
programis
calledalgd2.c,
andis
displayed
in
Appendix
A.
The instructions for running
this
program arein
Appendix
B.
Also,
an exampleis
shownin
Appendix B.
Dijkstra's
Shortest Path Algorithm
can alsobe
usedto
find
the
shortest pathbetween
one node and all other nodesin
the
network.To do
this,
the
algorithmis
run untilEVERY
nodeis
permanently labeled.
This is
accomplishedby
changing
the
iteration
phasesothat
instead
ofiterating
untilthe
destination
nodeis
permanently
labeled,
include
a"for
loop" sothe
iteration
phaseis
completedfor
each nodein
the
network.Then
the
distances
in
the
distance array
willcorrespond
to the
shortest pathdistance between
the
source node and all othernodes.
The
time
requiredto
runis
still0(n2).
A
C
programshowing
this
modification
is
called algd3.c andis
displayed in Appendix A.
The
instructions
for running
this
program and an example are shownin
Appendix B.
To
find
the
shortest pathfrom every
nodeto
all othernodes,
modify
Dijkstra's
algorithm
to
run oncefor
each nodein
the
network.This is
done
by
adding
a"for
loop" aroundthe initialization
anditeration
phases.The
time
requiredto
runthis
versionis 0(n3).
The C
programthat
performsthis
modificationis
calledalgd4.c and
is
presentedin Appendix A. The
instructions
for running
this
versionIf
the
distances between
the
nodes are all equalto
one,
then the
weight matrixwill equal
the
adjacency
matrix,
andthe
resulting
shortest pathdistance
willrepresent
the
number of nodesthat
have
to
be
traversed.
3.2
Bellman-Ford Shortest Path Algorithm
Bellman-Ford Shortest Path
Algorithm
canbe
usedto
find
the
distance
from
onenode
in
a networkto
every
other nodein
the
network.This
algorithm uses alabel-correcting
method.This
algorithm will workcorrectly
evenif
there
are arcswith negative
lengths
in
the network,
but
will not workif
there
are negativecycles
in
the
network.Initialization:
The
label
of a node representsthe
distance
from
the
source nodeto
that
node.Initially,
the
label
ofthe
source nodeis
setto
zero andthe
labels
of all othernodesare set
to
INFINITY
(a very large
numberfor
practical purposes).A
queueof
nodes, queue,
is
maintainedthroughout
this
algorithm.This
queue containsa
list
ofthe
nodesthat
needto
be further
inspected.
Initially,
the
source nodeis
Iteration:
During
the
iteration
phase, the
distance label
of anode,
y,
is
updatedto the
valueof
the
presentdistance from
the
source nodeto
y.Also,
the
new predecessor ofy
(tracing
back
to the
sourcenode)
is
found.
A
nodeis
taken
from
the
head
ofthe
queueduring
eachiteration.
Call
this
nodex.
All
ofthe
successors of node x areinspected.
If
the
distance
from
the
sourcenode, s, to
a successor of nodex,
say
nodey,
is
lessened
by
going
through x, then
the
distance label for
nodey
is
resetto the
smaller value.The
predecessorfor
node
y
is
setto
node x.Node y
is
addedto the
queueto
be
inspected
later.
Therefore,
if
a node'sdistance label
is
reduced, that
nodeis
placedin
the
queue.An improvement
ofthis
algorithm was suggestedby
d'Esopo
and refinedby
Pape.
Instead
ofalwaysplacing
the
node atthe tail
ofthe queue,
a node canbe
added
to the tail
orhead
ofthe
queue.It is
placed atthe
tail
of queueif it
has
never
been
in
the
queuebefore.
However,
if
a nodehas been
in
the
queuebefore,
it is
placed atthe
head
ofqueue,
allowing
it
to
be
reinspectedimmediately,
sothat the
labels
of allthe
nodesthat
were reachedby
means ofthat
node canbe
shortened
first.
This
shortensthe time
requiredto
executethe
algorithmby
If
there
are negative cyclesin the network, this
algorithm will not work.It
willtry
to
continually
reducethe
distance
by
going
around and aroundthe
negativecycle.
The
networkrepresentation
for
this
algorithmis
aforward
star,
making
it
ideal
for
sparse networksfrom
amemory
viewpoint.A
C implementation
ofthis
algorithm
is
called algbfl.c and canbe found
in Appendix A. The instructions for
running
this
program andanalyzing
the
results arein
Appendix B.
An
exampleis
alsodisplayed
in
Appendix
B.
This
algorithm caneasily be
modifiedto
find
the
shortest pathsbetween
all pairsof nodes.
The
algorithmis
run ntimes:
oncefor
each node asthe
source node.This is
accomplishedby
putting
a"for
loop"aroundthe
initialization
anditeration
phases.
The
C
programthat
performsthis
modificationis
called algbf2.c andis
shown
in Appendix A. The instructions
for
running
this
version and an exampleare
in Appendix B.
It is difficult
to
estimatethe
number oftimes
a node will enter andleave
the
queue
for
ageneral network model.The
worst caseis
representedby
a complete3.3
Floyd-Warshall Algorithm
In
some casesit is
necessary
to
computethe
shortest pathbetween
all pairs ofnodes, that
is,
between
all n *(n
-1)
ordered pairs of nodesin
the
network.Floyd-Warshall
Algorithm
willbe
usedin
this
case.This
algorithmis
adynamic
programming
algorithm which meansthe
problemis
solvedby
dividing
it into
smaller
subproblems,
solving
the subproblems,
andsaving
the
answersin
atabular
format.
The
combination of allthe
solutions ofthe
subproblems aidsin
solving
the
main problem.This
algorithm works evenif
there
are negative arc weightsin
the
network.In
addition,
it
willfind any
negative cycles.The
computationalcomplexity
ofthis
algorithm
is
0(n3).
The Floyd-Warshall Algorithm is
based
onWarshall's
algorithmfor computing
transitive
closure8of a matrix
for
a network.The input
to the
algorithmis
an nx nweight matrix.
Starting
withthis
weightmatrix,
ndifferent
matrices arebuilt
sequentially.
The
algorithminserts
a nodeinto
a path wheneverit is beneficial
to that
pathto
do
so.8
Initialization:
Given
weightmatrix,
MATRIX,
initialize
MATRIX;,
to
0
for
i
=0,
1,...
,n-l.PATH
is
an n x n matrixin
whichthe
i,jth
elementis
the
nodethat
is
the
predecessorof node
i.
Initialize
PATH^
suchthat
i
if
MATRIX,.
* ooPATHI
"-1
ifMATRll
- -<
for i
=0,1,...
, n-1j
=0,1,...
, n-1Iteration:
The
input
matrixis
the
weight matrix:MATRIX0.
Compute
MATRIX1
from
MATRIX0,
MATRTX2from
MATRIX1,
and soon,
until MATRTXnhas
been
computed.
The
rule usedfor computing
the
sequence of matricesis:
MATRIX;/*
=
MATRIX;,
(2)
MATRIX;/1 =
min(
MATRTXijh-1/
MATRIX^1
+
MATRIX^1)
(3)
k
=h-l
for h
=1, 2,
..., n andk
=In
the
first
iteration,
the
matrixcontains
direct distances
and equation(2)
is
used.In iteration
k,
nodek
is
inserted
into
the
pathfrom
nodei
to
nodej
if
the
distance
from
nodei
to
nodek
plusthe
distance
from
nodek
to
nodej
is
less
than the
current
distance
from
nodei
to
nodej.
This
actionis
representedby
the
minimization operation
in
equation(3).
Thus,
the
distance
from
nodei
to
nodej
is
reducedby inserting
nodek
into
the
path.The PATH
matrixis
updatedduring
eachiteration.
In iteration
k,
if
nodek is
inserted into
the
pathfrom
nodei
to
nodej,
PATH;,
is
replacedby
the
currentvalue of
PATHkj.
The i,jth
element ofMATRLXncorrespondsto the
shortestdistance from
nodei
to
node
j
in
the
network.If
there
are no negativecycles, then the
non-diagonalentries
in
the
final
matrix,
MATRIX",
representthe
shortestdistances.
If
the
network
does have
somenegativecycles,
then there
willbe
some negativevaluesin
the
matrix entries onthe
diagonal,
andthe
non-diagonal entries will notrepresent
the
shortestdistances.
The
reasonthere
willbe
negative valuesin
the
entries on
the
diagonal
is
asfollows.
The
algorithm worksby
inserting
anode,
k,
into
the
pathfrom
nodei
to
nodej,
if
the
weight of arc(Lk)
plusthe
weight ofweight matrix).
If
i
=j
andthe
weight of arc(i,k)
plusthe
weight of arc(k,j)
results
in
a negativevalue, then this
value willbe less
than the
weight ofthe
pathfrom
i
to
j
wheni
=j
(which
is
always0 in
a weight matrix).Therefore,
there
is
a negative weight path
from
nodei
to
nodek
andback
to
nodei (node
j).
This
forms
a negativecyclethat
includes
nodesi
andk,
andmay
include
other nodesin
the
network also.The
non-diagonal entries will notbe
accuratebecause
a pathfrom
the
sourcenode
to
adestination
nodethat
is
part of a negative cycle cannotbe
a shortestpath
because
a path with a smaller weight can alwaysbe
found
by
continuing
around
the
negative cycle.The C
program writtento implement this
algorithmis
called algfw.c.This
implementation
tests
for
a negative cycle andhalts
when oneis
found.
The
program
listing
is
displayed in Appendix A.
Instructions
for
running
the
program and
analyzing
the
results arein
Appendix B.
Two
examples are alsoChapter
4
Analysis
and
Results
The
algorithmsresearched
were analyzedusing
three
considerations: storagerequirements,
computationalcomplexity,
and actualprocessing
time.
The
number ofnodes
in
a given networkis
n andthe
number of arcsis
m.Computational
complexity
is
the
study
ofthe
number of operations requiredby
analgorithm.
Most
shortest path algorithms consist oftwo
operations: addition andminimization.
Both
operations are representedin
the
following
equation:WEIGHT;
=min(
WEIGHTi,
WEIGHT^^
+MATRIX^;)
for
each successornode,
i,
of node recentThe
equationis
usedto
determine
if
the
"distance"from
the
source nodeto
nodei
canbe
reducedby
going
through the
mostrecently permanently
labeled
node(which
then
would
become
nodei's
predecessor node).MATRTX^^i
is
the
distance between
the
most
recently permanently labeled
node and nodei.
WEIGHTj
representsthe
currentdistance between
the
source node and nodei (which may be
reducedthroughout
the
course of
the
program).WEIGHTrecent
representsthe
distance between
the
source nodeFor
somealgorithms, the
computational
complexity
will not changefor
a generaldirected
graph.However,
for
the
Bellman-Ford
Algorithm,
the
number of operationswill
vary
depending
onthe
network.For
this case, the
worst possible number ofoperations
has
to
be
computed.4.1
Dijkstra's Shortest Path Algorithm
The
networkis
madeto
look like
it
contains all arcs possibleby
assigning
arclengths
ofINFINITY
to
non-existent arcs.Therefore,
the time
it
takes
to
find
the
shortestpath
depends
onthe
numberofnodes,
andnotthe
number ofarcsin
the
network.
One
row ofthe
weightmatrixis inspected
for
eachiteration
ofthe
outermostloop
of
the
algorithm.The
outermostloop
is
executed n-1times
for
the
worst case(when
the
destination
nodeis
permanently
labeled
last).
As
more nodes getpermanently
labeled,
the
number of additions and rninimizations neededto
modify
the
temporary
labels
decreases.
The inner
loop
is
usedto
find
the
smallest
temporarily
labeled
nodefor
the
ith
rowofthe
matrix.The
first
time the
outer
loop
is
executed,
n -2
additions and n -2
minimizations are requiredto
examine all
the
successors ofnodei.
Also,
n-2
rrrinimizations(comparisons)
arethrough
the
outerloop,
n -3
additions and n -
3
minhnizations are required
to
examine all
the
successors of nodei.
Also,
n-3
nunimizations areneededto
find
the
smallesttemporarily
labeled
node.The
third time through the
loop,
n -4
additions and n -
4
minimizations
are needed... and so on.
Therefore,
the total
number of additions required
by
this
methodis
(n
-l)(n
-2) /
2.
The
total
number of minimizations required
is
(n
-l)(n
-2).
This
resultsin
a computationtime
ofapproximately
3/
2
* (n2-
3n
+2).
This is
onthe
order of n2.The
actualrunning
time
ofthe
algorithmdepends
onthe
proximity
ofthe
destination
nodeto the
sourcenode.If
the
destination
nodeis
very
closeto the
sourcenode,
it
willbe permanently labeled
soonerthan
if it is
the
farthest
nodefrom
the
sourcenode.The
secondversionofDijkstra's
Algorithm
uses alinked adjacency
list
structure.The
number of operationsis
notlessened,
but
the
number oftests
is
lessened.
Because
instead
oflooping
for
all nodesin
the
networkto
find
the
successors ofthe
mostrecently
permanently labeled
node, the
program stepsthrough
alinked
list
of successors.To illustrate
this point,
consider a100-node
network with asource node
having
only
5
immediate
successors.Version
1
ofDijkstra's
Algorithm
(algdl.c)
wouldhave
to test
each of99
nodesin
the
first
iteration
to
check
if
any
are successors ofthe
source nodebefore
the
program candetermine
if
the
temporary
label
canbe
shortened.However,
version2
ofDijkstra's
Algorithm
(algd2.c)
stepsthrough
the
linked list
of5
successors,
withouthaving
For
version3
ofDijkstra's
Algorithm,
the
versionthat
was modifiedto
find
the
shortest path
between
the
source node and all other nodes(algd3.c),
the
computation
time is
stillproportional
to
n2.This
is
the
same asthe
worst casefor
the
singlesource/
singledestination
version ofDijkstra's
Algorithm,
because
eachnode must
be
permanently labeled.
In
version4,
Dijkstra's
original algorithmis
repeated oncefor
each node asthe
sourcenode.
To
find
the
shortest pathbetween
all pairs of nodesin
the
networkfor
this version,
(algd4.c)
the
number of additionsand minimizationswillincrease
n
times.
The
computationtime
willbe
proportionalto
n3.If
the
graphis
notweighted,
the
weight matrix ofthe
network equalsthe
adjacency
matrix.In
this
case,
the
logical
operations,
and andor,
canbe
substituted
for
addition and minimizationto
save some computationtime.
The
storage requiredfor
the
Dijkstra Shortest Path
Algorithm,
versions1, 3,
and4,
consistsofmemory for
the
weightmatrix andthe three
arraysusedfor
keeping
track
ofpermanently labeled
nodes,
nodedistances
from
the
source,
andpredecessor nodes.
The
resulting
storage requirementis
n2+
3n.
The
storagerequired
for
version2
is
n +3m
for
the
linked adjacency
list,
and3n
for
the three
arrays used
for
storing
the
queue,
nodedistances
from
the
source,
and4.2
Bellman-Ford Shortest Path
Algorithm
The
difference
between
Dijkstra's Shortest
Path Algorithm
andthe Bellman-Ford
Shortest Path Algorithm is
that
in
Dijkstra's
algorithm,
nodes are given apermanent
label
once.In
the
first
version ofthe
Bellman-Ford Algorithm
anodeis
inspected
many
times
andits
label may be
correctedeachtime.
For
this
reason,
it
canbe
usedfor
networks with negative arcweights,
whereDijkstra's
algorithmcannot.
Each
nodecanenterthe
queue(be
labeled)
asmany
as n-1
times.
This
requires a computational
complexity approximately
proportionalto
n3at worst.
However,
for
mostcases,
it
willbe less
than this.
Version
2,
the
version ofthe
Bellman-Ford Shortest Path
Algorithm
modifiedto
computethe
shortest pathsbetween
all pairs ofnodes,
requiresa computationalcomplexity,
atworst,
ntimes
greater
than the
originalBellman-Ford
algorithm.Again,
for
mostcases,
it
willbe
less
than this.
The
storage required consists ofmemory for
the
forward
star structure(pointer,
target,
and weightarrays)
andthe
distance,
queue,
and predecessor arrays.The
resulting
storage requirementis
4n
+2m.
If
the
networkis
sparse,
m n *(n
-1),
the
Bellman-Ford Algorithm is
moreefficient
to
usethan the
versionofDijkstra's Algorithm
to
find
the
shortest path4.3
Floyd-Warshall Algorithm
The Floyd-Warshall
Algorithm
uses ann xn weightmatrix.A
total
of nmatricesare computed:
MATRIX0,
MATRIX1,
...,
MATRIX""1.
Since
each matrix consistsofn2
elements,
atotal
ofn3elements must
be
computedthroughout the
course ofthe
algorithm.The
computation of each element requires one addition and oneminimization.
Therefore,
the
computationalcomplexity
ofthe
basic
algorithmis
proportional
to
2n3.
However,
the
actualprocessing
time
canbe
reducedby
noting
that
for:
MATRIX;*
=
min
[
MATRIX;^"1),
(MATRIX^1* +
MATRIX,/1')
]
i
*j,
i
*k,
andj
*k.
By including
atest
for
these
casesin
the
for
loops
ofthe
programfor
the
Floyd-Warshall
Algorithm,
the
number of additions canbe
reduced
to
n(n-l)(n
-2)
andthe
number of minimizations canbe
reducedto
n(n-
l)(n
-2).
The
resulting
computationalcomplexity
is
2n(n
-l)(n
-2),
whichis
still proportional
to
2n3.
However,
this
modification canonly be
madefor
networks without negative
cycles,
because
the
entries onthe
diagonal
ofthe
matrix are used
to tell
if
a negative cyclehas
been found.
This
modificationThe
executiontime
canbe
reduced evenfurther for
sparse graphsby
including
a
test
for
the
case whereMATRIX^
=INFINITY
and
MATRIX^
=INFINITY. This
will eliminate
the
addition and minimization operationsfor
these cases,
atthe
expense of
the time
neededto
executethe
extratests.
However,
the
computationtime
is
still0(n3).
Storage is
requiredfor
one nx nmatrix,
whichthe
algorithmkeeps
writing
overfor
eachiteration.
Also,
an n x n matrix canbe
usedto
storethe
predecessorarray.
Therefore,
atotal
of 2n2 units of storageis
required.If
the
graphis
notweighted,
the
weight matrix ofthe
network equalsthe
adjacency
matrix.In
this
case,
the
logical
operations,
and andor,
canbe
substituted
for
addition and minimizationto
save some computationtime.
A
very
small amount of additional storagemay be
neededfor
eachalgorithm,
over and above what
has been
stated,
for
counters,
flags,
and so on.This
willdepend
onhow
the
algorithmis
implemented
and what computerlanguage
is
4.4
Time Trials
The implementations
ofthe
algorithmsthat
are comparedin
this
section are shownin
Appendix A.
Comparisons
are madefirst
with a sparsenetwork,
in
whichthe
numberof arcs
is
muchless
than
n *(n
-1).
Next,
comparisons are made with a completenetwork,
in
whichthere
are n *(n
-1)
arcs.4.4.1
Sparse
Network
The
first
set of comparisons were madeusing
asparse,
100
node network.There
were
191
arcsin
this
network.The
time trials
were run onanIBM PS/2 Model
70
(20
MHz).
Dijkstra's Shortest Path Algorithm
(version
3)
was comparedto the
Bellman-Ford
Algorithm
(version
1)
for
the
casewherethe
shortestpathbetween
a single source node and all other nodes
in
the
networkis
computed.The
following
table
displays
the
resultsfor
each program.Dijkstra
algd3.c
Bellman-Ford
algbfl.c
.09 sec
<
.01 secTable
4-1
Comparison
ofDijkstra
andBellman-Ford
Algorithms
for
aSparse Network
The
Bellman-Ford Algorithm
wasfaster
than
Dijkstra's Algorithm
for
the
sparseThe
algorithms were againcompared
using
the
sparse100
node network.This
time
the
case wherethe
shortest pathsbetween
all pairs of nodes was computedusing
allthree
algorithms(version
4
ofthe
Dijkstra Algorithm
and version2
ofthe
Bellman-Ford Algorithm
were used).Table 4-2
displays
the
results.Dijkstra
algd4.c
Bellman-Ford
algbf2.c
Floyd-Warshall
algfw.c
9.39
sec0.17
sec1.00
secTable 4-2
Comparison
ofDijkstra,
Bellman-Ford,
andFloyd-Warshall
Algorithms
for
aSparse Network
Again,
the
Bellman-Ford
Algorithm
provedto
be
the
fastest
atfinding
the
shortestpath
for
the
sparse network.4.4.2
Complete Network
The
second set oftiming
comparisons was madeusing
acomplete,
60-node
network.
There
were3540
arcsin
this
network.The
timing
comparisons wererun on an
IBM PS/2 Model 70
(20
MHz).
Dijkstra's
Shortest
Path Algorithm
(version
3)
wascomparedto the
Bellman-Ford Algorithm
(version
1)
for
the
caseDijkstra
algd3.c
.05 sec
Bellman-Ford
algbfl.c
.06sec
Table
4-3
Comparison
ofDijkstra
andBellman-Ford
Algorithms
for
aComplete Network
For
the
completenetwork,
it
canbe
seenthat the
speed ofthe
Dijkstra Shortest
Path Algorithm
is
comparable
to the
speed ofthe
Bellman-Ford Algorithm.
Next,
the
speed ofthe
algorithms was comparedfor
the
case wherethe
shortestpath
between
all pairs of nodesis
computed.Table
4-4
displays
the
timing
results.
Dijkstra
algd4.c
Bellman-Ford
algbf2.c
Floyd-Warshall
algfw.c
2.69
sec3.36
sec2.24
secThe Floyd-Warshall
Algorithm
provedto
be
the
fastest
algorithmfor
this case,
followed closely
by
the
Dijkstra
Algorithm.
NOTE: The
resultsfor
the
complete networktuning
example cannotbe
accurately
compared
to the
results ofthe
sparse networktuning
examplebecause
the
sparseChapter
5
Conclusions
A
precise comparison ofdifferent
shortest path algorithmsusing
a generalizednetworkcannot
be
performedaccurately
because
onealgorithmmay
workbetter
than
anotherin
aparticular
situation,
ormay depend
onwherethe
destination
nodeis in
relationto the
sourcenode.
Also,
variouslimitations may be
presentin
different
situations,
i.e.,
limited
computer storage
resources,
computing
power,
etc..These limitations
may
supportthe
use of one algorithm over another
for
a specific circumstance.A dense
networkis
a networkin
whichthe
number of arcsis
closeto
or equalto
n *
(n
1),
the
number of arcsin
a complete network.A
sparse networkis
a networkin
whichthe
number of arcsis
muchless
than
n *(n
-1).
Any
ofthe
algorithmsthat
use aforward
star orlinked adjacency list
networkrepresentation are
best
to
useif
the
networkis
sparse orsmall,
and computer storageis
at a rninimum.The
forward
star andlinked adjacency list
network representationsfor
input
files
take
up far less
computer storagethan
aweightmatrix representationfor
If
computer storageis
not at apremium, then
the
speed ofthe
algorithms canbe
compared
to
be
used as abasis for
determining
the
best
algorithm.From
the
analysisof computational