-
Notifications
You must be signed in to change notification settings - Fork 4
/
dfs_recursive.cpp
70 lines (64 loc) · 1.08 KB
/
dfs_recursive.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// A c++ program to demonstrate DFS traveral on undirected graph.
/*
TEST CASE
INPUT:
Enter the no of edges
7
1 2
1 3
1 5
2 4
2 6
3 7
5 6
Enter the starting node
2
OUTPUT:
2 1 3 7 5 6 4
*/
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
vector<int>nodes[1000];
bool visited[1000] = { false };
void dfs_recursive(int current){
if(!visited[current]){
cout<<current<<" ";
visited[current] = true;
for(vector<int>::iterator it=nodes[current].begin(); it!=nodes[current].end(); ++it)
if(visited[*it]==false)
dfs_recursive(*it);
}
}
int main()
{
int edges,a,b;
cout<<"Enter the no of edges"<<endl;
cin>>edges;
for(int i=0;i<edges;i++){
cin>>a>>b;
nodes[a].push_back(b);
nodes[b].push_back(a);
}
cout<<endl;
//Adj list representation
for(int i=0;i<1000;i++)
{
if(!nodes[i].empty())
{ cout<<"[ "<<i<<" ]"<<"-->";
for(vector<int>::iterator it=nodes[i].begin();
it!=nodes[i].end();++it)
{
cout<<*it<<"-->";
}
cout<<"NULL"<<endl;
}
}
int start;
cout<<"\nEnter the starting node"<<endl;
cin>>start;
dfs_recursive(start);
cout<<endl;
return 0;
}