VOOZH about

URL: https://www.geeksforgeeks.org/dsa/graph-implementation-using-stl-for-competitive-programming-set-1-dfs-of-unweighted-and-undirected/

⇱ Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)

Last Updated : 23 Jul, 2025

We have introduced Graph basics in Graph and its representations

In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. 

Following is an example undirected and unweighted graph with 5 vertices.  

👁 8


Below is an adjacency list representation of the graph.  

👁 9 (1)


We use vectors in STL to implement graphs using adjacency list representation. 

  • vector: A sequence container. Here we use it to store adjacency lists of all vertices. We use vertex numbers as the index in this vector.

The idea is to represent a graph as an array of vectors such that every vector represents the adjacency list of a vertex. Below is a complete STL-based C++ program for DFS Traversal

Implementation:


Output
0 1 2 3 4 

Time complexity : O(V+E), where V is the number of vertices in the graph and E is the number of edges in the graph. This is because the code performs a Depth First Search (DFS) on the graph, which takes O(V+E) time, as it visits each vertex once and visits all its adjacent vertices.

Space complexity :  O(V), where V is the number of vertices in the graph. This is because the code uses an adjacency list representation of the graph and maintains a visited array to keep track of visited vertices, both of which have a size of O(V). Additionally, the call stack of the DFSUtil function has a space complexity of O(V) in the worst case, when all vertices are reachable from a single vertex.

Below are related articles: 
Graph implementation using STL for competitive programming | Set 2 (Weighted graph) 
Dijkstra’s Shortest Path Algorithm using priority_queue of STL 
Dijkstra’s shortest path algorithm using set in STL 
Kruskal’s Minimum Spanning Tree using STL in C++ 
Prim’s algorithm using priority_queue in STL

Comment
Article Tags:
Article Tags: