-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdfs.cpp
More file actions
56 lines (56 loc) · 1.21 KB
/
dfs.cpp
File metadata and controls
56 lines (56 loc) · 1.21 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
55
56
#include<bits/stdc++.h>
using namespace std;
int main ()
{
int n,m,a,b,temp,i;
stack <int> trav;
cout << "Enter how many nodes you want" << endl;
cin >> n;
cout << "Enter how many edges you want" << endl;
cin >> m;
vector<int> data[n];
for (i=0;i<m;i++)
{
cout << "Enter an edge" << endl;
cin >> a >> b;
data[a-1].push_back(b);
data[b-1].push_back(a);
}
trav.push(temp);
int visited[n];
for (i=0;i<n;i++)
{
visited[i] = 0;
}
cout << "data is " << endl;
for (i=0;i<n;i++)
{
for (int j = 0;j<data[i].size();j++)
{
cout << data[i][j] << " ";
}
cout << endl;
}
cout << "Enter from which node you want to start" << endl;
cin >> temp;
trav.push(temp);
while (trav.size() != 0)
{
temp = trav.top();
trav.pop();
for (i=0;i<data[temp-1].size();i++)
{
if (visited[data[temp-1][i]] != 1)
{
trav.push(data[temp-1][i]);
}
}
if (visited[temp-1] != 1)
{
visited[temp-1] = 1;
cout << temp << " ";
}
}
cout << endl;
return 0;
}