scipy.sparse.csgraph.

construct_dist_matrix#

scipy.sparse.csgraph.construct_dist_matrix(graph, predecessors, directed=True, null_value=np.inf)#

從前導矩陣建構距離矩陣

在版本 0.11.0 中新增。

參數:
grapharray_like 或 sparse

有向或無向圖的 N x N 矩陣表示。如果是密集矩陣,則非邊緣以零或無限大表示。

predecessorsarray_like

每個節點的前導矩陣 (請參閱下方「Notes」)

directedbool, optional

如果為 True (預設值),則對有向圖進行操作:僅沿著路徑 csgraph[i, j] 從點 i 移動到點 j。如果為 False,則對無向圖進行操作:演算法可以沿著 csgraph[i, j] 或 csgraph[j, i] 從點 i 進行到點 j。

null_valuebool, optional

用於不相連節點之間距離的值。預設值為 np.inf

回傳值:
dist_matrixndarray

沿著前導矩陣指定的路徑,節點之間距離的 N x N 矩陣。如果路徑不存在,則距離為零。

Notes

前導矩陣的形式由 shortest_path 傳回。前導矩陣的第 i 列包含從點 i 出發的最短路徑資訊:每個條目 predecessors[i, j] 都給出了從點 i 到點 j 的路徑中前一個節點的索引。如果點 i 和 j 之間不存在路徑,則 predecessors[i, j] = -9999

範例

>>> import numpy as np
>>> from scipy.sparse import csr_array
>>> from scipy.sparse.csgraph import construct_dist_matrix
>>> graph = [
... [0, 1, 2, 0],
... [0, 0, 0, 1],
... [0, 0, 0, 3],
... [0, 0, 0, 0]
... ]
>>> graph = csr_array(graph)
>>> print(graph)
<Compressed Sparse Row sparse array of dtype 'int64'
    with 4 stored elements and shape (4, 4)>
    Coords  Values
    (0, 1)  1
    (0, 2)  2
    (1, 3)  1
    (2, 3)  3
>>> pred = np.array([[-9999, 0, 0, 2],
...                  [1, -9999, 0, 1],
...                  [2, 0, -9999, 2],
...                  [1, 3, 3, -9999]], dtype=np.int32)
>>> construct_dist_matrix(graph=graph, predecessors=pred, directed=False)
array([[0., 1., 2., 5.],
       [1., 0., 3., 1.],
       [2., 3., 0., 3.],
       [2., 1., 3., 0.]])