C++ programs for the implementation of Depth-first search(DFS) for a given graph

/* Write C++ programs for the implementation of Depth-first search(DFS) for a given graph */

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];
 
main()
{
int m;
cout <<"enterno of vertices";
cin >> n;
cout <<"ente no of edges";
cin >> m;
cout <<"\nEDGES \n";
for(k=1;k<=m;k++)
{
cin >>i>>j;
cost[i][j]=1;
}
 
cout <<"enter initial vertex";
cin >>v;
cout <<"ORDER OF VISITED VERTICES";
cout << v <<" ";
visited[v]=1;
k=1;
while(k<n)
{
for(j=n;j>=1;j--)
if(cost[v][j]!=0 && visited[j]!=1 && visit[j]!=1)
{
visit[j]=1;
stk[top]=j;
top++;
}
v=stk[--top];
cout<<v << " ";
k++;
visit[v]=0; visited[v]=1;
}
}

OUTPUT

enterno of vertices9
ente no of edges9

EDGES
1 2
2 3
2 6
1 5
1 4
4 7
5 7
7 8
8 9
enter initial vertex1
ORDER OF VISITED VERTICES1 2 3 6 4 7 8 9 5

Editorial Team
Editorial Team

We are a group of young techies trying to provide the best study material for all Electronic and Computer science students. We are publishing Microcontroller projects, Basic Electronics, Digital Electronics, Computer projects and also c/c++, java programs.

31 thoughts on “C++ programs for the implementation of Depth-first search(DFS) for a given graph

  1. will u plz tell me what is the use of visit[] array over here???
    and this code is randomly showing some result for the isolated graphs??
    plz help me out

  2. iwant to give me or explain how can that alogrithem in graph
    doing
    such that
    deep first earch
    breadth search
    critical path
    give me defintion

  3. this program is good.but i want Program for traversing a graph through DepthFirstSearch . please hlp me

  4. tree should be am i right?
    1
    / | \
    2 4 5
    / \ | 5 to 7 is backward edge
    3 6 7
    |
    8
    |
    9

    my question is how can I separate for 3 table?
    table 1 should include 1, 2, 3, 6
    table 2 should include 2, 4, 8, 9
    table 3 should include 5

  5. tree should be am i right?
    ——-1
    –/— |— \
    -2 —-4 —5
    / \ —-| ******5 to 7 is backward edge
    3 6— 7
    ———|
    ———8
    ———|
    ———9

    my question is how can I separate for 3 table?
    table 1 should include 1, 2, 3, 6
    table 2 should include 2, 4, 8, 9
    table 3 should include 5

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in