楼主只需自己 添加一个 把 邻接矩阵转换为邻接集的方法, 就能完工。
其中邻接集的字典数据有误。正确的邻接集字典数据、邻接矩阵如下:
# 邻接矩阵
AdjMatrix =[
[0, 1, 1, 1, 1, 1, 0, 0], # a
[0, 0, 1, 0, 1, 0, 0, 0], # b
[0, 0, 0, 1, 0, 0, 0, 0], # c
[0, 0, 0, 0, 1, 0, 0, 0], # d
[0, 0, 0, 0, 0, 1, 0, 0], # e
[0, 0, 1, 0, 0, 0, 1, 1], # f
[0, 0, 0, 0, 0, 1, 0, 1], # g
[0, 0, 0, 0, 0, 1, 1, 0] # h
]
for x in AdjMatrix:
for y in x:
print(y,end=' ')
print()
# 邻接集的字典
G = { 'a':set('bcdef'),
'b':set('ce'),
'c':set('d'),
'd':set('e'),
'e':set('f'),
'f':set('cgh'),
'g':set('fh'),
'h':set('fg') }
out_degrees = dict((u, 0) for u in G)
in_degrees = dict((u, 0) for u in G)
for u in G:
out_degrees[u] = len(G[u])
for u in G:
for v in G[u]:
in_degrees[v] += 1
print(out_degrees)
print(in_degrees)
输出:
0 1 1 1 1 1 0 0
0 0 1 0 1 0 0 0
0 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0
0 0 1 0 0 0 1 1
0 0 0 0 0 1 0 1
0 0 0 0 0 1 1 0
{'a': 5, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 3, 'g': 2, 'h': 2}
{'a': 0, 'b': 1, 'c': 3, 'd': 2, 'e': 3, 'f': 4, 'g': 2, 'h': 2}