Recursive C++ implementation of Depth First Search Program in C++

Introduction
In this article we are going to do an assignment based on the depth first search of graph. 

Problem Statement

Represent a given graph using adjacency matrix and traverse each node using Depth first search

Solution 

The core idea of depth first search of a graph is , starting from any vertex just keep on visiting next vertex suspending the remaining vertices connected to it .
As per given in problem statement , adjacency matrix is used to represent the graph.


Concept of Depth First Search ( DFS ) using Stack

The concept of DFS will be more clear with the example given below ..
Suppose we have to find the depth first search of above graph.  
The depth first search of graph will be :  0 1 2 3 4
More than one answers for depth first search are possible.

#C++ Program for Depth First Search

Download code here
#include<iostream>
using namespace std;

void dfs_rec (int v, int visit  [], int u);

int adj[20][20];

int main()
{
    int v,e,a,b;

    cout<<"Enter the number of vertices :";

    cin>>v;

//  int adj[v][v];

    for ( int i=0 ; i<v ; i++)

        for ( int j=0 ; j<v ; j++)
        {
                adj[i][j] = 0;
        }

        cout<<"Enter the number of edges : ";

        cin>>e;

        for ( int i=0;i<e;i++)

        {
            cout<<"Enter the edge (Starting and ending point) : ";

            cin>>a>>b;

            adj [a] [b] = adj [b] [a] = 1;

        }

        int visited [v];

        for ( int i=0;i<v;i++)

        visited [i] =0;

        cout<<"\t\t  The Depth First Search of your graph is : ";

        dfs_rec(0,visited,v);

        cout<<"\n\n";


}
void dfs_rec(int v,int visit[],int u)
{
    cout<<v;

    visit[v] = 1;

    for ( int j=0;j<u;j++)

    {
        if ( adj [v] [j] == 1 && visit [j] ==0)

            {
                dfs_rec ( j,visit,u );
            }
    }
}


Note :  This code is successfully compiled and run under Linux distribution Ubuntu 18.04 LTS environment .   

Output :

Enter the number of vertices :5
Enter the number of edges : 7
Enter the edge (Starting and ending point) : 0 1
Enter the edge (Starting and ending point) : 0 2
Enter the edge (Starting and ending point) : 1 2
Enter the edge (Starting and ending point) : 1 4
Enter the edge (Starting and ending point) : 2 3
Enter the edge (Starting and ending point) : 2 4
Enter the edge (Starting and ending point) : 4 3
      
  The Depth First Search of your graph is : 01234