0
点赞
收藏
分享

微信扫一扫

Python邻接矩阵邻接表转换


tags: Python GT

写在前面

学图论当然要学其中的算法, 学算法的基础在数据结构, 当然也少不了程序. 虽然不是专门研究图论, 但是能根据算法写出代码, 才算是真正掌握了这些概念了吧.

下面用Python实现图论中图结构的邻接表以及邻接矩阵, 都采用Python内置的列表数据类型实现.

代码

def matrix2table(martrix):
result = []
N = len(matrix)
for i in range(N):
tmp1 = []
for j in range(N):
if matrix[i][j]:
tmp1.append(j)
result.append(tmp1)
return result


def table2matrix(table):
ret = []
N = len(table)
for i in range(N):
tmp = [0] * N
for j in table[i]:
tmp[j] = 1
ret.append(tmp)
return ret


matrix = [
[0, 1, 0, 0, 0],
[0, 0, 1, 1, 0],
[0, 0, 0, 0, 1],
[1, 0, 0, 0, 1],
[0, 1, 0, 0, 0]
]

tb = matrix2table(matrix)
print(tb)

mat = table2matrix(tb)
print(mat)

思路很简单, 在这里小小记录一下.


举报

相关推荐

0 条评论