Why is time complexity for BFS/DFS not simply O(E) instead of O(E+V)?

爱⌒轻易说出口 提交于 2020-08-18 05:35:33

问题


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).

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.

But, if V cannot be greater than E+1. So, in that case not having V in the time complexity, should work?


回答1:


If it is given that E = kV + c, for some real constants k and c then,
O(E + V) = O(kV + c + V) = O(V) = O(E) and your argument is correct.

An example of this is trees.

In general, however, E = O(V^2), and thus we cannot do better than O(V^2).

Why not write just O(E) always?
Note that there might be cases when there are no edges in the graph at all (i.e. 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.

Thus, only writing O(E) won't do in general.




回答2:


V has to be included because both BFS and DFS rely on arrays of size |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. Thus, the time complexities of BFS and DFS scale on |V|.



来源:https://stackoverflow.com/questions/26750303/why-is-time-complexity-for-bfs-dfs-not-simply-oe-instead-of-oev

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!