Depth First Search

Adjacency List

In Java it is represented by:

The key is the node and value is the nodes connected to it

Time and Space Complexity

Complexity
Best Case
Worst Case

Time Complexity

O(V + E)

O(V + E)

Space Complexity

O(V)

O(V)

Code

Adjacency Matrix

It is represented in the following way:

The nodes connections are:

  • graph[i][j] = 1, the nodes are connected

    • if i==j, it means the node is connected to itself

  • graph[i][j] = 0, there is no connection between nodes

Time and Space Complexity

Complexity
Best Case
Worst Case

Time Complexity

O(V^2)

O(V^2)

Space Complexity

O(V)

O(V)

The best and worst time complexity for DFS using an adjacency matrix is the same, which is O(V^2), where V is the number of vertices in the graph. This is because we need to visit every vertex and check its adjacency matrix row, which takes O(V) time for each vertex.

The space complexity is O(V) as we need additional space to store the visited array, which has a size equal to the number of vertices. The space complexity is independent of the density of the graph because we always allocate space for all vertices.

It's important to note that the space complexity may vary if additional data structures or recursive calls are used within the DFS algorithm. The analysis provided here considers the space complexity of the core DFS algorithm with an adjacency matrix.

Code

Last updated