在python中,我注意到有人使用 defaultdict(list)
或类似的东西.你怎么写的 list<int> adj[n]
或 vector<vector<int>> adj(n)
在python中?
不会使用字典,而字典基本上是由 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