简体   繁体   中英

Calculating time complexity of DFS algorithm

I have been tasked with an assignment where I have to check if a group of people have a "close friendship". This is defined as a group of people where all persons in the group are friends with all other persons in the group. So far I have this as my algorithm:

1) Initialize vertices as not visited

2) Do a DFS traversal of the graph starting from any arbitrary vertex v, marking visited vertices as visited

3) If the DFS traversal visits all vertices, return true

4) If it does not, return false.

Now I have to calculate the time complexity. However, I am having a hard time with time complexity in general, and I am not entirely sure how to do this. The way I see it is that I go through all the vertices in my set, which would be... O(v)? Is this correct? And if it is, what do I do from here?

Since in DFS you visit all vertices only once, but you travel every edge to see whether that edge is taking you to a new vertex or to an already seen vertex, a very accurate measure of the complexity of DFS is O(#edges).

But O(#vertices) is generally an acceptable answer too to the complexity for DFS question, because when you see that an edge is not taking you to a new vertex, you don't explore it further.

So when asked, you can give either answer and explain the reasoning, because neither of them is wrong with supporting explanation.


But this may not be the answer to the actual question you are trying to solve. You are trying to find a closely connected group.

In graph terminology, a closely connected group of friends would be one where each friend node shares an edge with every other friend node. (Re-read your question - it actually literally says that.)

In the image below, majority of the graph is connected and other nodes are reachable from one node using DFTraversal. But close cohorts are the group of nodes with same color.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM