Program to traverse graphs using DFS.

#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
int main()
{
int cost[10][10],i,j,k,n,stk[10],top,v,visit[10],visited[10],m;
cout<<"Enter no of vertices : ";
cin>>n;
cout<<"Enter 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<<"Depth first search order is : ";
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;
}
cout<<"\n/*\nName-Sanjampreet Singh\nRoll Number-1507967\n*/";
return 0;
}

Output:


Comments

Popular posts from this blog

To create an html page with frames and frameset

1. Write a program to insert a new element at end as well as at a given position in an array in Java

1. To familiarize with network devices like switch, hub, routers and bridges in LaTex