-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbfs_undirected.cpp
More file actions
61 lines (50 loc) · 1.05 KB
/
Copy pathbfs_undirected.cpp
File metadata and controls
61 lines (50 loc) · 1.05 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
57
58
59
60
61
/*For un-directed graph*/
#include<iostream>
#include<vector>
#include<queue>
#define MAX 100
using namespace std ;
vector<int> adj[MAX] ;
bool visited[MAX] ;
queue<int> q ;
void initialize(int nodes){
for (int i = 1; i<=nodes ;i++){
visited[i] = false ;
}
}
void bfs(int current){
q.push(current) ;
cout << current << "\t" ;
visited[current] = true ;
while (!q.empty()){
int v = q.front();
q.pop() ;
for(int i = 0; i<adj[v].size() ; i++){
if (visited[adj[v][i]] == false){
q.push(adj[v][i]);
cout << adj[v][i] << "\t" ;
visited[adj[v][i]] = true ;
}
}
}
}
int main ()
{
int nodes , edges , i , x , y ;
cout << "Enter the number of nodes\t" ;
cin >> nodes ;
cout << "Enter the total number of edges\t" ;
cin >> edges ;
cout <<"Enter the edges pairs of the graph (eg : a b , for a-b)\n";
for (i = 0; i<edges ;i++){
cin >> x >> y ;
adj[x].push_back(y) ;
adj[y].push_back(x) ;
}
initialize(nodes) ;
cout << "Breadth first traversal\n";
//for (int i = 1 ; i<=nodes ;i++){
bfs(1) ;
//}
return 0 ;
}