python - 用字典在python中制作邻接列表以解决图形问题的替代方法?(像矢量> 在 C++ 中)
问题描述
在 python 中,我注意到人们使用defaultdict(list)
或类似性质的东西制作图表。你是怎么写的list<int> adj[n]
还是vector<vector<int>> adj(n)
用python?
不会使用基本上unordered_maps
会使大图上的运行时间变慢的字典吗?
解决方案
使用 OOPs 方式!取自Graphs 和它的表示。感谢@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
推荐阅读
- postgresql - 使用 java 和 Postgres DB 绑定的 Azure 函数
- javascript - 如何使用 vue 提交从对象数组中提取数据的预填充表单
- google-maps - 如何通过 React Native 在谷歌地图中获得星星和评论
- flutter - 将行文本与右角对齐
- python - 无法在 Django 中导入本地模块
- mysql - 即使表没有所有ID,如何在查询中获取所有结果
- java - WebSphere 中 LinkageError 导致的 ServiceConfigurationError
- javascript - 未设置显示 cookie
- r - 如何将chr转换为数字
- javascript - 输入提交字段上的 jQuery 事件