T22 WeightedGraphs
T22 WeightedGraphs
25 15 0
i h g f e d c b a
D
Weighted Graphs
Data Structures & Algorithms
5
CS@VT 2000-2009 McQuain
Dijkstra's Algorithm Trace
35 20
25 35 25 15 0
i h g f e d c b a
Continuing:
S = {a, b, h}
D
S = {a, b, h, c}
D
S = {a, b, h, c, e}
D
S = {a, b, h, c, e, g}
D
S = {a, b, h, c, e, g, f}
D
35 20
25
25 15 0
i h g f e d c b a
35 20 30 35 25 35 25 15 0
i h g f e d c b a
35 20 30 35 25 35 25 15 0
i h g f e d c b a
35 20 30 35 25 35 25 15 0
i h g f e d c b a
Weighted Graphs
Data Structures & Algorithms
6
CS@VT 2000-2009 McQuain
Dijkstra's Algorithm Trace
Continuing:
S = {a, b, h, c, e, g, f, d}
D
S = {a, b, h, c, e, g, f, d, i}
D
a
i
g
f
e
d
c
b
h
25
15
10
5
10
20
15
5
25
10
The corresponding tree is shown
at left. As described, the
algorithm does not maintain a
record of the edges that were used,
but that can easily be remedied.
35 20 30 35 25 35 25 15 0
i h g f e d c b a
35 20 30 35 25 35 25 15 0
i h g f e d c b a
Weighted Graphs
Data Structures & Algorithms
7
CS@VT 2000-2009 McQuain
Limitations
Dijkstra'sSSAD Algorithm only works for graphs with non-negative weights.
See the Bellman-Ford Algorithm, which works even if the weights are negative,
provided there is no negative cycle (a cycle whose total weight is negative).
Weighted Graphs
Data Structures & Algorithms
8
CS@VT 2000-2009 McQuain
Minimal Spanning Tree
Given a weighted graph, we would
like to find a spanning tree for the
graph that has minimal total weight.
The total weight of a spanning tree is
the sum of the weights of its edges.
We want to find a spanning tree T,
such that if T' is any other spanning
tree for the graph then the total
weight of T is less than or equal to
that of T'.
a
i
g
f
e
d
c
b
h
25
15
10
5
10
20
15
5
25
10
Weighted Graphs
Data Structures & Algorithms
9
CS@VT 2000-2009 McQuain
J arnik-Prim MST Algorithm
By modifying DijkstrasSSAD Algorithm to build a list of the edges that are
used as vertices are added, and storing the distance from nodes to the current
tree (rather than from nodes to the source) we obtain Prims Algorithm (V
J arnik, 1930 and R C Prim, 1957).
It turns out that this algorithm does, in fact, create a spanning tree of minimal
weight if the graph to which it is applied is connected.
Since the complex steps in Prims algorithm are the same as Dijkstras, no
detailed example is traced here.
QTP: why does Dijkstra's SSAD Algorithm not necessarily
find a minimum-weight spanning tree?
Weighted Graphs
Data Structures & Algorithms
10
CS@VT 2000-2009 McQuain
J arnik-Prim MST Algorithm Trace
a
i
g
f
e
d
c
b
h
25
15
10
5
10
20
15
5
25
10
A B C D E F G H I
----------------------------------
0 15 25 inf inf inf inf inf inf
A 25 inf 10 inf inf 5 25
25 inf 10 inf inf B 15
20 inf B 10 5 15
20 inf 10 E 15
20 inf E 15
20 inf H
E 10
C
a
i
g
f
e
d
c
b
h
25
15
10
5
10
20
15
5
25
10