Life Hacks


      

a program to traverse a graph using Depth First Search Algorithm



#include<iostream.h>

#include<conio.h>

#include<stdlib.h>

int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10];

void 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:

clip_image002

Leave a Reply