-
Notifications
You must be signed in to change notification settings - Fork 0
/
DFS.cpp
56 lines (56 loc) · 1.19 KB
/
DFS.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct graph
{
int V;
list<int>*adj;
};
struct graph*createGraph(int v)
{
struct graph*g=(struct graph*)malloc(sizeof(struct graph));
g->V=v;
g->adj=new list<int>[v];
return g;
}
void addEdge(struct graph*g,int src,int dst)
{
g->adj[src].push_back(dst);
}
void DfsUtil(struct graph*g,int start,bool visited[])
{
visited[start]=true;
cout<<start<<" ";
list<int>::iterator it;
for(it=g->adj[start].begin();it!=g->adj[start].end();it++)
{
if(!visited[*it])
DfsUtil(g,*it,visited);
}
}
void DFS(struct graph*g,int start)
{
int v=g->V;
bool*visited=new bool[v];
for(int i=0;i<v;i++)
visited[i]=false;
DfsUtil(g,start,visited);
}
int main()
{
int v,ch,src,dst,start;
cout<<"ENTER THE TOTAL VERTEX";
cin>>v;
struct graph*g=createGraph(v);
cout<<"GRAPH CREATED\n";
cout<<"NOW YOU CAN ENTER EDGES PAIR\n";
do
{
cin>>src>>dst;
addEdge(g,src,dst);
cout<<"WANT TO ENTER MORE(1 for 'YES' 0 for 'NO')";
cin>>ch;
}while(ch!=0);
cout<<"ENTER THE STARTING VERTEX";
cin>>start;
DFS(g,start);
}