Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the time complexity of DFS to detect a cycle in an undirected graph O(|V|) and not O(|V| + |E|)?

Can anyone explain to me in detail why and how the upper bound of DFS to detect a cycle in an undirected graph be O(|V|) ?

like image 663
Sazz Avatar asked Mar 04 '23 03:03

Sazz


1 Answers

A graph without cycles has at most |V| - 1 edges (it's a forest). Therefore if the DFS discovers |V| edges or more then it already found a cycle and terminates. The runtime is accordingly bounded by O(|V|).

like image 165
Yakov Galka Avatar answered Apr 30 '23 10:04

Yakov Galka