python - 使用 Numpy 或 Scipy 从邻接矩阵连接组件
问题描述
我有以下邻接矩阵:
array([[0, 1, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0]])
可以这样画:
我的目标是识别连通图 ABC 和 DEFG。似乎深度优先搜索算法是我需要的,Scipy实现了它。所以这是我的代码:
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import depth_first_order
import numpy as np
test = np.asarray([
[0, 1, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0],
[0, 0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 1, 0]
])
graph = csr_matrix(test)
result = depth_first_order(graph, 0)
但我没有得到结果:
>>> result
(array([0, 1, 2]), array([-9999, 0, 1, -9999, -9999, -9999, -9999]))
那是什么array([-9999, 0, 1, -9999, -9999, -9999, -9999])
?此外,在文档中,他们谈论的是稀疏矩阵而不是邻接矩阵。但是根据定义,邻接矩阵似乎是一个稀疏矩阵,所以我不清楚。
解决方案
虽然您确实可以使用 DFS 来查找连接的组件,但 SciPy 使用scipy.sparse.csgraph.connected_components
. 用你的例子:
In [3]: connected_components(test)
Out[3]: (2, array([0, 0, 0, 1, 1, 1, 1], dtype=int32))
推荐阅读
- node.js - 在 Nodejs 中为 firebase-admin NPM 初始化与 firebase 的多个连接失败
- html - 在 HTML 页面中嵌入概念页面
- python - PyAudio 安装错误:构建轮子失败
- linux - Linux 服务器上的 Umbraco 9(Kestrel 服务)- 部署代码更改后站点死机
- mysql - 尝试使用 SQL 查询在后端将两个表连接在一起,但看不到其中一个表的数据
- javascript - ioslides R markdown 页脚在每页上都有图像
- python - 如何从 Linux 上的 python 控制 labview 中的实验?
- gremlin - Gremlin with Neptune:使用具有先前边缘值的数学结果过滤边缘
- asp.net-core-identity - 我们如何使用 IUserClaimsPrincipalFactory
? - c# - 如何使用 VPC 终端节点 URL 将文件上传到 Amazon S3 存储桶?