我正在处理有向图,我很困惑Alberto Miranda对Quora的解释如何得出时间复杂度O(n+m)
[我假设他的意思是{{1}对于顶点和边缘]。
可以在时间O(n + m)中将边缘列表L转换为邻接列表表示A.然后,可以在时间O(n + m)上对表示A执行DFS,总共为O(n + m)。
这是我对从一种表现形式转换为另一种表现形式的理解:
从边缘列表到邻接列表的转换:
我的理解是,我们所要做的就是遍历每条边并添加到每个边列表中第一个顶点的邻接列表中,从而给出O(V+E)
的时间复杂度。我错过了什么?我假设O(E)
和n
变量分别引用顶点和边,但可以随意纠正我。
从邻接列表到边缘列表的转换:
我试过这个转换只是为了看他是否指的是逆转换。要从邻接列表切换,我必须遍历每个顶点m
,然后遍历每个V
的边缘,V
给我E
}。
我编写了代码以便检查
这是我代表的图表: 需要注意的是,顶点3不是邻接列表表示中的关键字,因此不包括在从邻接列表到边缘列表的转换中。
O(V+E)
给出结果
from collections import defaultdict
class AdjacencyListGraph:
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
class EdgeListGraph:
def __init__(self):
self.graph = []
def addEdge(self, u, v):
self.graph.append([u, v])
def addAllEdgesAtOnce(self, edgeList):
self.graph = edgeList
def edgeListToAdjacencyList(edgeListGraph):
adjacencyListGraph = AdjacencyListGraph()
for edge in edgeListGraph.graph:
adjacencyListGraph.addEdge(edge[0], edge[1])
return adjacencyListGraph
def adjacencyListToEdgeList(adjacencyListGraph):
edgeListGraph = EdgeListGraph()
for vertex in adjacencyListGraph.graph.keys():
for child in adjacencyListGraph.graph[vertex]:
edgeListGraph.addEdge(vertex, child)
return edgeListGraph
edgeList = [
[1, 2],
[2, 3],
[1, 3],
[4, 1],
[4, 5],
[5, 6],
[6, 4]
]
edgeListGraph = EdgeListGraph()
edgeListGraph.addAllEdgesAtOnce(edgeList)
adjacencyListGraph = edgeListToAdjacencyList(edgeListGraph)
print(adjacencyListGraph.graph)
# trying to reverse the conversion
convertedEdgeListGraph = adjacencyListToEdgeList(adjacencyListGraph)
print(convertedEdgeListGraph.graph)
所以我的转换工作正常。
这些帖子与邻接列表有关,但没有提及时间复杂性。
答案 0 :(得分:0)
My understanding is that all we have to do is go through each edge and add to the adjacency list of that first vertex in each edge list thereby giving the time complexity of O(E).
Converting an edge list to the adjacency list is indeed O(E). There are E edges, so there should be E operations. However, printing (or presenting) the adjacency list itself is O(V+E). Here is why.
Think of, if there was no edge between any vertex, you have to still go through every vertex and you will end up with something like this:
{1: [], 2: [], 3: [], 4: [],... v: []}
So V number of operations is a must. On top of it, you have to print neighboring vertices for each vertex, if edges do exist. You have to print the neighboring vertices in total E times. That sums to O(V+E).
To sum up: convert from edge list to adjacency list: O(E) presenting the adjacency list (independent from conversion): O(V+E)