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

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` `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[], ``int` `V)` `{` `    ``vector<``bool``> visited(V, ``false``);` `    ``for` `(``int` `u=0; u *adj = new vector[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> 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> 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> 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> adj = new ArrayList<>(V);` `        ``List> adj = ``new` `ArrayList<>(V);`   `        ``for` `(``int` `i = ``0``; i < V; i++) {` `            ``adj.add(``new` `ArrayList());` `        ``}`   `        ``// 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 *adj = new vector[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 > 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 > 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 > 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> adj = new List>(V);` `        ``List > adj = ``new` `List >();`   `        ``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

 ``

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.

If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Previous
Next
Similar Reads
Complete Tutorials