├── README.md └── k_shortest_paths.py /README.md: -------------------------------------------------------------------------------- 1 | k_shortest_paths contains a function with the same name. This function uses Networkx (version 2.2.0). 2 | Said function computes the k shortest paths using Yen's algorithm (https://en.m.wikipedia.org/wiki/Yen%27s_algorithm) 3 | -------------------------------------------------------------------------------- /k_shortest_paths.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | import copy as cp 3 | 4 | def k_shortest_paths(G, source, target, k = 1, weight = 'weight'): 5 | # G is a networkx graph. 6 | # source and target are the labels for the source and target of the path. 7 | # k is the amount of desired paths. 8 | # weight = 'weight' assumes a weighed graph. If this is undesired, use weight = None. 9 | 10 | A = [nx.dijkstra_path(G, source, target, weight = 'weight')] 11 | A_len = [sum([G[A[0][l]][A[0][l + 1]]['weight'] for l in range(len(A[0]) - 1)])] 12 | B = [] 13 | 14 | for i in range(1, k): 15 | for j in range(0, len(A[-1]) - 1): 16 | Gcopy = cp.deepcopy(G) 17 | spurnode = A[-1][j] 18 | rootpath = A[-1][:j + 1] 19 | for path in A: 20 | if rootpath == path[0:j + 1]: #and len(path) > j? 21 | if Gcopy.has_edge(path[j], path[j + 1]): 22 | Gcopy.remove_edge(path[j], path[j + 1]) 23 | if Gcopy.has_edge(path[j + 1], path[j]): 24 | Gcopy.remove_edge(path[j + 1], path[j]) 25 | for n in rootpath: 26 | if n != spurnode: 27 | Gcopy.remove_node(n) 28 | try: 29 | spurpath = nx.dijkstra_path(Gcopy, spurnode, target, weight = 'weight') 30 | totalpath = rootpath + spurpath[1:] 31 | if totalpath not in B: 32 | B += [totalpath] 33 | except nx.NetworkXNoPath: 34 | continue 35 | if len(B) == 0: 36 | break 37 | lenB = [sum([G[path[l]][path[l + 1]]['weight'] for l in range(len(path) - 1)]) for path in B] 38 | B = [p for _,p in sorted(zip(lenB, B))] 39 | A.append(B[0]) 40 | A_len.append(sorted(lenB)[0]) 41 | B.remove(B[0]) 42 | 43 | return A, A_len 44 | --------------------------------------------------------------------------------