Graph Theory37 sections · 1633 units
Open in Course

Time Complexity of DFS

How fast is it?

DFS visits every vertex exactly once (thanks to the visited array). For each vertex, it loops through all its neighbors. Across all vertices, the total number of neighbor iterations equals the number of edges times two (for undirected graphs) or the number of edges (for directed graphs).

So DFS runs in O(V+E)O(V + E) time where VV is vertices and EE is edges. This is linear in the size of the graph. DFS is fast. For most graphs, EE is proportional to VV, so it is effectively O(n)O(n) where nn is the number of vertices.

Space complexity is O(V)O(V) for the data structures used.