Time complexity of depth-first graph algorithm [closed]

半世苍凉 提交于 2019-12-03 22:38:25
gabitzish

The time complexity for DFS is O(n + m). We get this complexity considering the fact that we are visiting each node only once and in the case of a tree (no cycles) we are crossing all the edges once.

For example, if the start node is u, and the end node is v, we are thinking at the worst-case scenario when v will be the last visited node. So we are starting to visit each the first neighbor's of u connected component, then the second neighbor's connected component, and so on until the last neighbor's connected component, where we find v. We have visited each node only once, and didn't crossed the same edge more than once.

it will be O(n+m) if the graph is given in the form of adjacency list but if the graph is in the form of adjacency matrix then the complexity is O(n*n), as we have to traverse through the whole row until we find an edge.

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