-
Notifications
You must be signed in to change notification settings - Fork 47
/
DFS
101 lines (94 loc) Β· 1.7 KB
/
DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include<iostream>
using namespace std;
#include<stdlib.h>
#define ma 100
/////////////////////////////
struct vertex
{
int d;
struct vertex *next;
};
int n;
struct vertex *v[ma]={NULL};
int visit[ma]={0};
///////////////////////////////
void value(int &a,int &b)
{
cout<<"enter source and destination"<<endl;
cin>>a>>b;
}
//////////////////////////////////
void create(struct vertex *v[],int n,int e)
{
int i,j;
int a,b;
for(j=0;j<e;j++)
{
value(a,b);
struct vertex *New=NULL,*ptr=NULL;
New=new struct vertex;
New->d=b;
New->next=NULL;
if(v[a]==NULL)
{
v[a]=New;
}
else
{
ptr=v[a];
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=New;
}
}
}
///////////////////////////////
void print(struct vertex *v[],int n,int e)
{
int i;
for(i=0;i<n;i++)
{
cout<<i<<"->";
struct vertex *ptr=v[i];
while(ptr!=NULL)
{
cout<<ptr->d<<" -> ";
ptr=ptr->next;
}
cout<<endl;
}
}
////////////////////////////
void dfs(int i)
{
int j;
struct vertex *p;
cout<<i<<endl;
p=v[i];
visit[i]=1;
while(p!=NULL)
{
j=p->d;
if(visit[j]!=1)
{
dfs(j);
}
p=p->next;
}
}
////////////////////////////////////
int main()
{
int e;
cout<<"enter number of edge"<<endl;
cin>>e;
cout<<"enter number of vertices"<<endl;
cin>>n;
create(v,n,e);
print(v,n,e);
cout<<"enter source vertex "<<endl;
int s;
cin>>s;
cout<<"visited vertex are: "<<endl;
dfs(s);
}