當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python SciPy csgraph.shortest_path用法及代碼示例


本文簡要介紹 python 語言中 scipy.sparse.csgraph.shortest_path 的用法。

用法:

scipy.sparse.csgraph.shortest_path(csgraph, method='auto', directed=True, return_predecessors=False, unweighted=False, overwrite=False, indices=None)#

在正向或無向圖上執行最短路徑圖搜索。

參數

csgraph 數組、矩陣或稀疏矩陣,二維

表示輸入圖的 N x N 距離數組。

method 字符串 [‘auto’|'FW'|'D'],可選

用於最短路徑的算法。選項是:

‘auto’ - (default) select the best among ‘FW’, ‘D’, ‘BF’, or ‘J’

based on the input data.

‘FW’ - Floyd-Warshall algorithm.

Computational cost is approximately O[N^3]. The input csgraph will be converted to a dense representation.

‘D’ - Dijkstra’s algorithm with Fibonacci heaps.

Computational cost is approximately O[N(N*k + N*log(N))], where k is the average number of connected edges per node. The input csgraph will be converted to a csr representation.

‘BF’ - Bellman-Ford algorithm.

This algorithm can be used when weights are negative. If a negative cycle is encountered, an error will be raised. Computational cost is approximately O[N(N^2 k)], where k is the average number of connected edges per node. The input csgraph will be converted to a csr representation.

‘J’ - Johnson’s algorithm.

Like the Bellman-Ford algorithm, Johnson’s algorithm is designed for use when the weights are negative. It combines the Bellman-Ford algorithm with Dijkstra’s algorithm for faster computation.

directed 布爾型,可選

如果為 True(默認),則在有向圖上查找最短路徑:僅沿著路徑 csgraph[i, j] 從點 i 移動到點 j。如果為 False,則找到無向圖上的最短路徑:算法可以沿著 csgraph[i, j] 或 csgraph[j, i] 從點 i 前進到 j

return_predecessors 布爾型,可選

如果為 True,則返回大小為 (N, N) 的前驅矩陣。

unweighted 布爾型,可選

如果為真,則找到未加權的距離。也就是說,不是找到每個點之間的路徑以使權重之和最小化,而是找到使邊數最小化的路徑。

overwrite 布爾型,可選

如果為 True,則用結果覆蓋 csgraph。這僅適用於 method == ‘FW’ 且 csgraph 是密集的 c-ordered 數組且 dtype=float64 的情況。

indices 數組 或 int,可選

如果指定,則僅計算給定索引處的點的路徑。與方法 == 'FW' 不兼容。

返回

dist_matrix ndarray

圖節點之間距離的 N x N 矩陣。 dist_matrix[i,j] 給出圖上從點 i 到點 j 的最短距離。

predecessors ndarray

僅當 return_predecessors == True 時返回。 N x N 前驅矩陣,可用於重建最短路徑。前驅矩陣的第 i 行包含從點 i 開始的最短路徑信息:每個條目前驅[i, j] 給出從點 i 到點 j 的路徑中前一個節點的索引。如果點 i 和 j 之間不存在路徑,則前驅[i, j] = -9999

拋出

NegativeCycleError:

如果圖中有負循環

注意

按照目前的實現,Dijkstra 算法和 Johnson 算法不適用於具有 direction-dependent 距離的圖,當有向 == False 時。即,如果 csgraph[i,j] 和 csgraph[j,i] 是不等邊,method='D' 可能會產生不正確的結果。

如果可能存在多個有效解決方案,則輸出可能會因 SciPy 和 Python 版本而異。

例子

>>> from scipy.sparse import csr_matrix
>>> from scipy.sparse.csgraph import shortest_path
>>> graph = [
... [0, 1, 2, 0],
... [0, 0, 0, 1],
... [2, 0, 0, 3],
... [0, 0, 0, 0]
... ]
>>> graph = csr_matrix(graph)
>>> print(graph)
  (0, 1)    1
  (0, 2)    2
  (1, 3)    1
  (2, 0)    2
  (2, 3)    3
>>> dist_matrix, predecessors = shortest_path(csgraph=graph, directed=False, indices=0, return_predecessors=True)
>>> dist_matrix
array([0., 1., 2., 2.])
>>> predecessors
array([-9999,     0,     0,     1], dtype=int32)

相關用法


注:本文由純淨天空篩選整理自scipy.org大神的英文原創作品 scipy.sparse.csgraph.shortest_path。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。