53 lines
977 B
Python
53 lines
977 B
Python
A = "A"
|
|
B = "B"
|
|
C = "C"
|
|
#D = "D"
|
|
E = "E"
|
|
F = "F"
|
|
|
|
nodes = [A,B,C,E,F]
|
|
|
|
edges = {
|
|
(A,B,3),
|
|
(A,C,4),
|
|
# (B,D,5),
|
|
(B,E,2),
|
|
# (C,D,1),
|
|
# (D,E,2),
|
|
# (D,F,4),
|
|
(E,F,6)
|
|
}
|
|
|
|
def getadjacent(node, edges):
|
|
adjacent = set()
|
|
for (s,t,l) in edges:
|
|
if s == node:
|
|
adjacent.add( (t,l) )
|
|
elif t == node:
|
|
adjacent.add( (s,l) )
|
|
return adjacent
|
|
|
|
|
|
def spr(s,t, nodes, edges):
|
|
nodes = set(nodes)
|
|
m = { s:(0,[s])}
|
|
S = set([s])
|
|
S2 = set(S)
|
|
while S < nodes:
|
|
for s in set(S2):
|
|
S2.remove( s )
|
|
l,p = m[s]
|
|
for (ad,sl) in getadjacent(s, edges):
|
|
if ad not in S:
|
|
m[ad] = (l+sl,p+[ad])
|
|
else:
|
|
ad_l,_ = m[ad]
|
|
if ad_l > l+sl:
|
|
m[ad] = (l+sl,p+[ad])
|
|
S.add( ad )
|
|
S2.add( ad )
|
|
return m[t]
|
|
|
|
|
|
print( spr(A,F, nodes, edges) )
|
|
|