[英]Why is time complexity for BFS/DFS not simply O(E) instead of O(E+V)?
I know there's a similar question in stack overflow, where one person has asked, why time complexity of BFS/DFS is not simply O(V).我知道在堆栈溢出中有一个类似的问题,有人问过,为什么 BFS/DFS 的时间复杂度不是简单的 O(V)。
The appropriate answer given was that E can be as large as V^2 in case of complete graph, and hence it is valid to include E in time complexity.给出的适当答案是,在完整图的情况下,E 可以与 V^2 一样大,因此在时间复杂度中包含 E 是有效的。
But, if V cannot be greater than E+1.但是,如果 V 不能大于 E+1。 So, in that case not having V in the time complexity, should work?
那么,在这种情况下,时间复杂度中没有 V,应该可行吗?
If it is given that E = kV + c
, for some real constants k
and c
then,如果给定
E = kV + c
,对于一些实常数k
和c
那么,
O(E + V) = O(kV + c + V) = O(V) = O(E)
and your argument is correct. O(E + V) = O(kV + c + V) = O(V) = O(E)
你的论点是正确的。
An example of this is trees.这方面的一个例子是树木。
In general (ie, without any prior information), however, E = O(V^2)
, and thus we cannot do better than O(V^2)
.然而,一般而言(即,没有任何先验信息),
E = O(V^2)
,因此我们不能比O(V^2)
做得更好。
Why not write just O(E) always?为什么不总是只写 O(E)?
EDIT: The primary reason for always writing O(E + V)
is to avoid ambiguity.编辑:总是写
O(E + V)
主要原因是为了避免歧义。
For example, there might be cases when there are no edges in the graph at all (ie O(E) ~ O(1)
).例如,可能存在图中根本没有边的情况(即
O(E) ~ O(1)
)。 Even for such cases, we'll have to go to each of the vertex ( O(V)
), we cannot finish in O(1)
time.即使在这种情况下,我们也必须去每个顶点(
O(V)
),我们无法在O(1)
时间内完成。
Thus, only writing O(E)
won't do in general.因此,一般只写
O(E)
行不通的。
V has to be included because both BFS and DFS rely on arrays of size |V|必须包含 V,因为 BFS 和 DFS 都依赖于大小为 |V| 的数组to track which vertices have been processed/discovered/explored (whatever the case may be).
跟踪哪些顶点已被处理/发现/探索(无论情况如何)。 If a graph has 0 edges and 100000 vertices, such arrays will still take more time to initialize than they would if there were only 5 vertices.
如果一个图有 0 条边和 100000 个顶点,与只有 5 个顶点的情况相比,这样的数组仍然需要更多的时间来初始化。 Thus, the time complexities of BFS and DFS scale on |V|.
因此,BFS 和 DFS 的时间复杂度在 |V| 上缩放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.