图的邻接矩阵
# 图的邻接矩阵
class GraphAX:
def __init__(self, vertx, mat):
"""
vertx 顶点表的信息
mat 边的信息
:param vertx: 顶点集
:param mat: 边集信息
"""
vnum = len(vertx) # 顶点的个数
self.vertx = vertx #
self.mat = [mat[i][:] for i in range(vnum)]
"""
"""
def get_edge(self, vi, vj):
if vi not in self.vertx or vj not in self.vertx:
print("无效顶点")
return
i = self.vertx.index(vi)
j = self.vertx.index(vj)
return self.mat[i][j] # 如果返回的是1 说明是链接的 ,如果说明的不是这个东西则说明不是链接的
def create_matrix():
nodes = ['v0', 'v1', 'v2', 'v3', 'v4']
matrix = [[0, 1, 0, 1, 0],
[1, 0, 1, 0, 1],
[0, 1, 0, 1, 0],
[1, 0, 1, 0, 0],
[0, 1, 1, 0, 0]]
mygraph = GraphAX(nodes, matrix)
return mygraph
if __name__ == '__main__':
graph = create_matrix()
"""
打印顶点
打印边
打印度
"""
print(graph.vertx)
print(graph.mat)
图的邻接表
class Anode: # 边表信息
def __init__(self, edgedata, weight=0):
self.edgedata = edgedata
self.weight = weight
self.next = None
class Vnode: # 顶点表结点
def __init__(self, vertdata):
self.vertdata = vertdata
self.firsta = None
class Graph: # 图类
def __init__(self):
self.vertList = []
self.numvert = 0
def add_vert(self, key): # 添加到顶点表中
vertex = Vnode(key)
self.vertList.append(vertex)
self.numvert += 1
def add_edge(self, vert1, vert2, weight=0): # 添加边
i = 0
while i < len(self.vertList):
if vert1 == self.vertList[i].vertdata:
n1 = self.vertList[i]
break
i = i + 1
if i == len(self.vertList):
n1 = self.add_vert(vert1)
i = 0
while i < len(self.vertList):
if vert2 == self.vertList[i].vertdata:
n2 = self.vertList[i]
break
i = i + 1
if i == len(self.vertList):
n2 = self.add_vert(vert2)
j = self.vertList.index(n2)
p = Anode(j)
p.next = n1.firsta
n1.firsta = p
graph = Graph()
while True:
s = input("请输入图的顶点值,输入#结束")
if s == '#':
break
else:
graph.add_vert(s)
while True:
vert1, vert2 = input("请输入边的两个顶点, 用逗号隔开, 输入#结束").split(',')
if vert1 == '#':
break
else:
graph.add_edge(vert1, vert2)
for i in range(graph.numvert):
print(graph.vertList[i].vertdata, end='')
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/76970.html