-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDepth First Search.cpp
More file actions
54 lines (52 loc) · 1.08 KB
/
Depth First Search.cpp
File metadata and controls
54 lines (52 loc) · 1.08 KB
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
#include<iostream>
#include<stack>
#include<cstring>
#include<vector>
using namespace std;
vector< int > adj[100];
bool visited[100];
int n,e,u,v,x,y;
void DFS(int source)
{
int i;
stack <int> stack;
memset(visited,false,sizeof(visited));
stack.push(source);
while(!stack.empty())
{
u = stack.top();
cout<<u<<"->";
stack.pop();
visited[u] = true;
for(i=0; i< adj[u].size();i++)
{
v = adj[u][i];
if(visited[v]==false)
{
stack.push(v);
visited[v] = 2;
}
}
}
return;
}
int main()
{
int source;
cout<<"Enter number of vertices: ";
cin>>n;
cout<<"Enter number of edges: ";
cin>>e;
memset(adj,false,sizeof(adj));
cout<<"Enter vertex to vertex"<<endl;
while(e--)
{
cin>>x>>y;
adj[x].push_back(y);
adj[y].push_back(x);
}
cout<<"Enter the source to start the DFS traversal: ";
cin>>source;
DFS(source);
return 0;
}