Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
Last Updated :
14 Feb, 2023
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.

Below is an adjacency list representation of the graph.

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:
C++
// A simple representation of graph using STL,
// for the purpose of competitive programming
#include<bits/stdc++.h>
using namespace std;
// A utility function to add an edge in an
// undirected graph.
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
// A utility function to do DFS of graph
// recursively from a given vertex u.
void DFSUtil(int u, vector<int> adj[],
vector<bool> &visited)
{
visited[u] = true;
cout << u << " ";
for (int i=0; i<adj[u].size(); i++)
if (visited[adj[u][i]] == false)
DFSUtil(adj[u][i], adj, visited);
}
// This function does DFSUtil() for all
// unvisited vertices.
void DFS(vector<int> adj[], int V)
{
vector<bool> visited(V, false);
for (int u=0; u<V; u++)
if (visited[u] == false)
DFSUtil(u, adj, visited);
}
// Driver code
int main()
{
int V = 5;
// The below line may not work on all
// compilers. If it does not work on
// your compiler, please replace it with
// following
// vector<int> *adj = new vector<int>[V];
vector<int> adj[V];
// Vertex numbers should be from 0 to 4.
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
DFS(adj, V);
return 0;
}
Java
import java.util.*;
class Graph {
// A utility function to add an edge in an
// undirected graph.
static void addEdge(List<List<Integer>> adj, int u, int v) {
adj.get(u).add(v);
adj.get(v).add(u);
}
// A utility function to do DFS of graph
// recursively from a given vertex u.
static void DFSUtil(int u, List<List<Integer>> adj, boolean[] visited) {
visited[u] = true;
System.out.print(u + " ");
for (int i = 0; i < adj.get(u).size(); i++) {
if (!visited[adj.get(u).get(i)]) {
DFSUtil(adj.get(u).get(i), adj, visited);
}
}
}
// This function does DFSUtil() for all
// unvisited vertices.
static void DFS(List<List<Integer>> adj, int V) {
boolean[] visited = new boolean[V];
for (int u = 0; u < V; u++) {
if (!visited[u]) {
DFSUtil(u, adj, visited);
}
}
}
public static void main(String[] args) {
int V = 5;
// The below line may not work on all
// compilers. If it does not work on
// your compiler, please replace it with
// following
// List<List<Integer>> adj = new ArrayList<>(V);
List<List<Integer>> adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<Integer>());
}
// Vertex numbers should be from 0 to 4.
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
DFS(adj, V);
}
}
// this code is contributed by devendrasalunke
Python3
# A simple representation of graph using STL,
# for the purpose of competitive programming
# A utility function to add an edge in an
# undirected graph.
def addEdge(adj, u, v):
adj[u].append(v)
adj[v].append(u)
return adj
# A utility function to do DFS of graph
# recursively from a given vertex u.
def DFSUtil(u, adj, visited):
visited[u] = True
print(u, end = " ")
for i in range(len(adj[u])):
if (visited[adj[u][i]] == False):
DFSUtil(adj[u][i], adj, visited)
# This function does DFSUtil() for all
# unvisited vertices.
def DFS(adj, V):
visited = [False]*(V+1)
for u in range(V):
if (visited[u] == False):
DFSUtil(u, adj, visited)
# Driver code
if __name__ == '__main__':
V = 5
# The below line may not work on all
# compilers. If it does not work on
# your compiler, please replace it with
# following
# vector<int> *adj = new vector<int>[V]
adj = [[] for i in range(V)]
# Vertex numbers should be from 0 to 4.
adj = addEdge(adj, 0, 1)
adj = addEdge(adj, 0, 4)
adj = addEdge(adj, 1, 2)
adj = addEdge(adj, 1, 3)
adj = addEdge(adj, 1, 4)
adj = addEdge(adj, 2, 3)
adj = addEdge(adj, 3, 4)
DFS(adj, V)
# This code is contributed by mohit kumar 29.
C#
using System;
using System.Collections.Generic;
class Graph {
// A utility function to add an edge in an
// undirected graph.
static void AddEdge(List<List<int> > adj, int u, int v)
{
adj[u].Add(v);
adj[v].Add(u);
}
// A utility function to do DFS of graph
// recursively from a given vertex u.
static void DFSUtil(int u, List<List<int> > adj,
bool[] visited)
{
visited[u] = true;
Console.Write(u + " ");
for (int i = 0; i < adj[u].Count; i++) {
if (!visited[adj[u][i]]) {
DFSUtil(adj[u][i], adj, visited);
}
}
}
// This function does DFSUtil() for all
// unvisited vertices.
static void DFS(List<List<int> > adj, int V)
{
bool[] visited = new bool[V];
for (int u = 0; u < V; u++) {
if (!visited[u]) {
DFSUtil(u, adj, visited);
}
}
}
public static void Main(string[] args)
{
int V = 5;
// The below line may not work on all
// compilers. If it does not work on
// your compiler, please replace it with
// following
// List<List<int>> adj = new List<List<int>>(V);
List<List<int> > adj = new List<List<int> >();
for (int i = 0; i < V; i++) {
adj.Add(new List<int>());
}
// Vertex numbers should be from 0 to 4.
AddEdge(adj, 0, 1);
AddEdge(adj, 0, 4);
AddEdge(adj, 1, 2);
AddEdge(adj, 1, 3);
AddEdge(adj, 1, 4);
AddEdge(adj, 2, 3);
AddEdge(adj, 3, 4);
DFS(adj, V);
}
} // this code is contributed by devendra
JavaScript
<script>
// A simple representation of graph using STL,
// for the purpose of competitive programming
// A utility function to add an edge in an
// undirected graph.
function addEdge(adj,u,v)
{
adj[u].push(v);
adj[v].push(u);
}
// A utility function to do DFS of graph
// recursively from a given vertex u.
function DFSUtil(u,adj,visited)
{
visited[u] = true;
document.write(u+" ");
for (let i=0; i<adj[u].length; i++)
if (visited[adj[u][i]] == false)
DFSUtil(adj[u][i], adj, visited);
}
// This function does DFSUtil() for all
// unvisited vertices.
function DFS(adj,V)
{
let visited=new Array(V);
for(let i=0;i<V;i++)
{
visited[i]=false;
}
for (let u=0; u<V; u++)
if (visited[u] == false)
DFSUtil(u, adj, visited);
}
// Driver code
let V = 5;
// The below line may not work on all
// compilers. If it does not work on
// your compiler, please replace it with
// following
// vector<int> *adj = new vector<int>[V];
let adj=new Array(V);
for(let i=0;i<V;i++)
{
adj[i]=[];
}
// Vertex numbers should be from 0 to 4.
addEdge(adj, 0, 1);
addEdge(adj, 0, 4);
addEdge(adj, 1, 2);
addEdge(adj, 1, 3);
addEdge(adj, 1, 4);
addEdge(adj, 2, 3);
addEdge(adj, 3, 4);
DFS(adj, V);
// This code is contributed by unknown2108
</script>
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
Similar Reads
Depth First Search or DFS for a Graph In Depth First Search (or DFS) for a graph, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. This is similar to a tree, where we first completely traverse the left subtree and
13 min read
DFS in different language
Iterative Depth First Traversal of Graph Given a directed Graph, the task is to perform Depth First Search of the given graph.Note: Start DFS from node 0, and traverse the nodes in the same order as adjacency list.Note : There can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick
10 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS) Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we ca
4 min read
Difference between BFS and DFS Breadth-First Search (BFS) and Depth-First Search (DFS) are two fundamental algorithms used for traversing or searching graphs and trees. This article covers the basic difference between Breadth-First Search and Depth-First Search.Difference between BFS and DFSParametersBFSDFSStands forBFS stands fo
2 min read
Depth First Search or DFS for disconnected Graph Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Disconnected Graph Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given sour
7 min read
Printing pre and post visited times in DFS of a graph Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored
8 min read
Tree, Back, Edge and Cross Edges in DFS of Graph Given a directed graph, the task is to identify tree, forward, back and cross edges present in the graph.Note: There can be multiple answers.Example:Input: GraphOutput:Tree Edges: 1->2, 2->4, 4->6, 1->3, 3->5, 5->7, 5->8 Forward Edges: 1->8 Back Edges: 6->2 Cross Edges: 5-
9 min read
Transitive Closure of a Graph using DFS Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: GraphTr
8 min read
Variations of DFS implementations