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


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

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

用法:

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

從前驅矩陣構造距離矩陣

參數

graph 數組 或稀疏

有向圖或無向圖的 N x N 矩陣表示。如果密集,則非邊由零或無窮大表示。

predecessors array_like

每個節點的前驅的 N x N 矩陣(請參閱下麵的注釋)。

directed 布爾型,可選

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

null_value 布爾型,可選

用於未連接節點之間距離的值。默認為np.inf

返回

dist_matrix ndarray

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

注意

前驅矩陣的形式為 shortest_path 返回。前驅矩陣的第 i 行包含從點 i 開始的最短路徑信息:每個條目前驅[i, j] 給出從點 i 到點 j 的路徑中前一個節點的索引。如果點 i 和 j 之間不存在路徑,則前驅[i, j] = -9999

例子

>>> import numpy as np
>>> from scipy.sparse import csr_matrix
>>> 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_matrix(graph)
>>> print(graph)
  (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.]])

相關用法


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