除了使用字典以外,如何在python中创建邻接表? (类似于列表数组或c ++中向量的向量)

问题描述 投票:0回答:1

[在python中,我注意到人们使用defaultdict(list)或类似性质的东西制作图形。您如何在python中编写list<int> adj[n]vector<vector<int>> adj(n)

不会使用基本上为unordered_maps的字典会使大型图形的运行时间变慢吗?

python c++ adjacency-list
1个回答
0
投票

使用OOPS方式!取自Graphs and it's representations。感谢@DarrylG提供了它!

# A class to represent the adjacency list of the node 
class AdjNode: 
    def __init__(self, data): 
        self.vertex = data 
        self.next = None


# A class to represent a graph. A graph 
# is the list of the adjacency lists. 
# Size of the array will be the no. of the 
# vertices "V" 
class Graph: 
    def __init__(self, vertices): 
        self.V = vertices 
        self.graph = [None] * self.V 

    # Function to add an edge in an undirected graph 
    def add_edge(self, src, dest): 
        # Adding the node to the source node 
        node = AdjNode(dest) 
        node.next = self.graph[src] 
        self.graph[src] = node 

        # Adding the source node to the destination as 
        # it is the undirected graph 
        node = AdjNode(src) 
        node.next = self.graph[dest] 
        self.graph[dest] = node 
© www.soinside.com 2019 - 2024. All rights reserved.