edited by
12,208 views
34 votes
34 votes

Let $G$ be a graph with $n$ vertices and $m$ edges. What is the tightest upper bound on the running time of Depth First Search on $G$, when $G$ is represented as an adjacency matrix?

  1. $\Theta(n)$
  2. $\Theta(n+m)$
  3. $\Theta(n^2)$
  4. $\Theta(m^2)$
edited by

4 Answers

Best answer
30 votes
30 votes

Depth First Search of a graph takes $O(m+n)$ time when the graph is represented using adjacency list. In adjacency matrix representation, graph is represented as an $n * n$ matrix. To do DFS, for every vertex, we traverse the row corresponding to that vertex to find all adjacent vertices (In adjacency list representation we traverse only the adjacent vertices of the vertex). Therefore time complexity becomes $O(n^2)$.

Correct Answer: $C$

edited by
13 votes
13 votes

1. Depth-first search requires O(V + E) time if implemented with adjacency lists

2. Depth-first search requires O(V2) time if implemented with an adjacency matrix

edited by
2 votes
2 votes
DFS visits each vertex once and as it visits each vertex, we need to find all of its neighbours to figure out where to search next. Finding all its neighbours in an adjacency matrix requires O(V ) time, so overall the running time will be O(V2).
Answer:

Related questions

49 votes
49 votes
8 answers
3