替代在python中制作邻接列表与图形问题的字典?(如 C++ 中的 vector<vector<int&g

Alternate(s) to making adjaceny list in python with dictionary for graph problems? (like vector<vector<int>> in c++)

本文关键字:lt vector 字典 C++ 中的 int 问题 python 图形 列表      更新时间:2023-10-16

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

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

使用 OOPs 的方式! 取自图形及其表示形式。感谢@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