294
def floyd_warshall_array(G):
295
"""The Floyd-Warshall algorithm for all pairs shortest paths.
304
distance,pred : dictionaries
305
A dictionary, keyed by source and target, of shortest path
306
distance and predecessors in the shortest path.
310
This differs from floyd_warshall only in the types of the return
311
values. Thus, path[i,j] gives the predecessor at j on a path from
312
i to j. A value of None indicates that no path exists. A
313
predecessor of i indicates the beginning of the path. The
314
advantage of this implementation is that, while running time is
315
O(n^3), running space is O(n^2).
317
This algorithm handles negative weights.
320
# A weight that's more than any path weight
322
for u,v,d in G.edges(data=True):
336
dist[i][j] = 0 # arbitrary, just create slot
337
pred[i][j] = 0 # arbitrary, just create slot
343
dist_prev[i][j] = val
346
# no edge, distinct vertices
347
dist_prev[i][j] = HUGE_VAL
348
pred_prev[i][j] = -1 # None, but has to be numerically comparable
352
dist[i][j] = min(dist_prev[i][j], dist_prev[i][k] + dist_prev[k][j])
353
if dist_prev[i][j] <= dist_prev[i][k] + dist[k][j]:
354
pred[i][j] = pred_prev[i][j]
356
pred[i][j] = pred_prev[k][j]
364
# The last time through the loop, we exchanged for nothing, so
365
# return the prev versions, since they're really the current
367
return dist_prev, pred_prev
368
######################################################################
370
def floyd_warshall(G):
371
"""The Floyd-Warshall algorithm for all pairs shortest paths.
379
distance,pred : dictionaries
380
A dictionary, keyed by source and target, of shortest path
381
distance and predecessors in the shortest path.
385
This algorithm is most appropriate for dense graphs.
386
The running time is O(n^3), and running space is O(n^2)
387
where n is the number of nodes in G.
391
all_pairs_shortest_path()
392
all_pairs_shortest_path_length()
395
huge=1e30000 # sentinal value
396
# dictionary-of-dictionaries representation for dist and pred
398
# initialize path distance dictionary to be the adjacency matrix
399
# but with sentinal value "huge" where there is no edge
400
# also set the distance to self to 0 (zero diagonal)
402
# initialize predecessor dictionary
409
dist[u][v]=unbrs[v].get('weight',1)
414
dist[u][u]=0 # set 0 distance to self
419
if dist[u][v] > dist[u][w] + dist[w][v]:
420
dist[u][v] = dist[u][w] + dist[w][v]
421
pred[u][v] = pred[w][v]
425
298
def predecessor(G,source,target=None,cutoff=None,return_seen=None):