-
Notifications
You must be signed in to change notification settings - Fork 7
/
DFS_BFS.cpp
137 lines (110 loc) · 2.18 KB
/
DFS_BFS.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
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<bits/stdc++.h>
#define MAX 100001
using namespace std;
// intializing the graph
vector<int> v[MAX];
// intializing the visited array
int visited[MAX]={0};
void dfs(int start){
cout<<start<<" ";
// mark the current node as visited
visited[start]=1;
for(int i=0;i<v[start].size();i++)
{
// loop through all the nodes connected to current node
// if the node is not alreay marked visit it
if(!visited[v[start][i]])
{
dfs(v[start][i]);
}
}
}
void bfs(int start)
{
int current;
queue<int> q;
// push the source node to the queue
q.push(start);
// loop till the queue is empty
while(q.size()!=0)
{
// set current node to the first node in the queue
current = q.front();
q.pop();
// if current node isn't marked already visit it
if(!visited[current])
{
cout<<current<<" ";4
visited[current]=1;
}
for(int i=0;i<v[current].size();i++)
{
if(!visited[v[current][i]])
{
// push all nodes adjacent to the current node to the queue
cout<<v[current][i]<<" ";
visited[v[current][i]]=1;
q.push(v[current][i]);
}
}
}
}
int main()
{
int n,i,j,k,node,start,edges,u1,v1;
cout<<"Enter no of nodes and edges in a graph";
cin>>n>>edges;
for(i=1;i<=edges;i++)
{
cout<<"Enter the pair of nodes having an edge"<<endl;
cin>>u1>>v1;
v[u1].push_back(v1);
v[v1].push_back(u1);
}
cout<<"Enter the starting node:";
cin>>start;
cout<<"DFS Traversal:"<<endl;
dfs(start);
cout<<endl;
/* making all elements of visited array 0 */
for(i=0;i<100001;i++)
visited[i]=0;
cout<<"BFS Traversal:"<<endl;
bfs(start);
cout<<endl;
return 0;
}
//OUTPUT
/*
Enter no of nodes in a graph 5
Enter no of adjacent nodes
3
Enter the adjacent nodes
2
3
5
Enter no of adjacent nodes
3
Enter the adjacent nodes
1
4
5
Enter no of adjacent nodes
1
Enter the adjacent nodes
1
Enter no of adjacent nodes
1
Enter the adjacent nodes
2
Enter no of adjacent nodes
2
Enter the adjacent nodes
1
2
Enter the starting node: 1
DFS Traversal:
1 2 4 5 3
BFS Traversal:
1 2 3 5 4
*/