【数据结构】无向图:图的数据结构、遍历以及邻接表和邻接矩阵相互转换(1)

在只使用内置函数lenprint, input的条件下,实现Python3中对无向图的创建以及遍历,以及邻接表和邻接矩阵的转换,class来代替C中的struct

PS: 本文中的图均为无向图,转载需注明作者和出处。

《【数据结构】无向图:图的数据结构、遍历以及邻接表和邻接矩阵相互转换(1)》

图的数据结构

邻接表

《【数据结构】无向图:图的数据结构、遍历以及邻接表和邻接矩阵相互转换(1)》

构建邻接表的每个结点的数据类型
class Vertex(object):
    def __init__(self, data=None, n=None, first_edge=None):
        self.data = data
        self.first_edge = first_edge
        self.next = n
以邻接表的方式存储图,传入顶点数目,按照邻接表的结构来依次传入每一行的数据,并返回一个结点列表
def create_adj_list(vertex_num):
    def func(vertex):
        data1 = input("Input next vertex: ")
        vertex.next = Vertex(int(data1)) if data1 != "#" else None
        if vertex.next is not None:
            func(vertex.next)

    vertex_list = [Vertex(x) for x in range(vertex_num)]  # 生成结点对象,并存入结点列表
    for i in range(vertex_num):  # 依次给结点列表中的结点对象赋予第一个子元素
        data = input("Input vertex%d's first edge's vertex: " % i)
        vertex_list[i].first_edge = Vertex(int(data)) if data != "#" else None  # 输入"#" 则表示无下一个元素
        if vertex_list[i].first_edge is not None:  # 如果结点列表对象的第一个子元素不为空,则调用 func 递归生成后面的子元素
            func(vertex_list[i].first_edge)
    return vertex_list

邻接矩阵

《【数据结构】无向图:图的数据结构、遍历以及邻接表和邻接矩阵相互转换(1)》

实际上他是这样的

《【数据结构】无向图:图的数据结构、遍历以及邻接表和邻接矩阵相互转换(1)》

构建邻接矩阵的数据类型
class Matrix(object):
    def __init__(self, matrix):
        self.vertex_list = [i for i in range(len(matrix))]
        self.matrix = matrix
创建邻接矩阵
matrix = Matrix([[0, 1, 1, 0, 1], [1, 0, 1, 0, 0], [1, 1, 0, 1, 0], [0, 0, 1, 0, 1], [1, 0, 0, 1, 0]])

未完待续……………………

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/w3300306/article/details/80462766
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞