Let G be a graph with n vertices and m edges. What is the tightest upp...
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 x 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(n2)
View all questions of this test
Let G be a graph with n vertices and m edges. What is the tightest upp...
Depth First Search (DFS) on Graph with Adjacency Matrix
DFS is an algorithm used to traverse and search a graph. It starts at a source vertex and explores as far as possible along each branch before backtracking. The algorithm is implemented using a stack data structure. The running time of DFS depends on the number of vertices and edges in the graph.
Adjacency Matrix Representation
An adjacency matrix is a square matrix used to represent a graph. The rows and columns of the matrix represent the vertices of the graph, and the entries represent the edges. If there is an edge between vertices i and j, then the entry (i, j) or (j, i) is set to 1. Otherwise, the entry is set to 0.
Running Time of DFS
The running time of DFS on a graph with n vertices and m edges can be expressed as O(n^2) in the worst case. This is because the algorithm visits each vertex once and each edge once. The time complexity of checking whether an edge exists between two vertices in an adjacency matrix is O(1). Therefore, the total time complexity of DFS on a graph with adjacency matrix representation is O(n^2).
Explanation of Options
a) O(n) - This option is incorrect because DFS has to visit each vertex and edge in the graph, so the running time must be at least O(n^2).
b) O(mn) - This option is incorrect because the number of edges in a graph can be at most n(n-1)/2, which is less than mn. Therefore, O(mn) cannot be a tight upper bound on the running time.
c) O(n^2) - This option is correct because DFS visits each vertex and edge once, and the time complexity of checking whether an edge exists between two vertices in an adjacency matrix is O(1). Therefore, the total time complexity of DFS on a graph with adjacency matrix representation is O(n^2).
d) O(mn) - This option is incorrect because the number of edges in a graph can be at most n(n-1)/2, which is less than mn. Therefore, O(mn) cannot be a tight upper bound on the running time.