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


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

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

用法:

scipy.sparse.csgraph.depth_first_tree(csgraph, i_start, directed=True)#

返回由深度優先搜索生成的樹。

請注意,深度優先搜索生成的樹不是唯一的:它取決於每個節點的子節點的搜索順序。

參數

csgraph 數組 或稀疏矩陣

表示壓縮稀疏圖的 N x N 矩陣。輸入的 csgraph 將被轉換為 csr 格式進行計算。

i_start int

起始節點的索引。

directed 布爾型,可選

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

返回

cstree 企業社會責任矩陣

從 csgraph 繪製的深度優先樹的 N x N 定向 compressed-sparse 表示,從指定節點開始。

注意

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

例子

以下示例顯示了在簡單的 four-component 圖上計算深度優先樹(從節點 0 開始):

input graph           depth first tree from (0)

     (0)                         (0)
    /   \                           \
   3     8                           8
  /       \                           \
(3)---5---(1)               (3)       (1)
  \       /                   \       /
   6     2                     6     2
    \   /                       \   /
     (2)                         (2)

在壓縮稀疏表示中,解決方案如下所示:

>>> from scipy.sparse import csr_matrix
>>> from scipy.sparse.csgraph import depth_first_tree
>>> X = csr_matrix([[0, 8, 0, 3],
...                 [0, 0, 2, 5],
...                 [0, 0, 0, 6],
...                 [0, 0, 0, 0]])
>>> Tcsr = depth_first_tree(X, 0, directed=False)
>>> Tcsr.toarray().astype(int)
array([[0, 8, 0, 0],
       [0, 0, 2, 0],
       [0, 0, 0, 6],
       [0, 0, 0, 0]])

請注意,生成的圖是跨越該圖的有向無環圖。與廣度優先樹不同,如果給定圖包含循環,則深度優先樹不是唯一的。如果上述解決方案從連接節點 0 和 3 的邊開始,結果將會有所不同。

相關用法


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