替代方法)在 python 中使用字典制作邻接列表来解决图形问题? (就像 c++ 中的 vector<vector<int>>)
Alternate(s) to making adjaceny list in python with dictionary for graph problems? (like vector<vector<int>> in c++)
在 python 中,我注意到人们使用 defaultdict(list)
或类似的东西制作图表。
python中的list<int> adj[n]
或vector<vector<int>> adj(n)
怎么写?
使用基本上 unordered_maps
的字典不会使 运行 在大图上的时间变慢吗?
使用面向对象的方式!
摘自 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
在 python 中,我注意到人们使用 defaultdict(list)
或类似的东西制作图表。
python中的list<int> adj[n]
或vector<vector<int>> adj(n)
怎么写?
使用基本上 unordered_maps
的字典不会使 运行 在大图上的时间变慢吗?
使用面向对象的方式! 摘自 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