-
Notifications
You must be signed in to change notification settings - Fork 0
/
BFS.cpp
81 lines (77 loc) · 1.47 KB
/
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
#include <iostream>
#include <queue>
using namespace std;
int adj_mat[50][50] = {0,0};
int visited[50] = {0};
void bfs(int s, int n, string arr[])
{
bool visited[n];
#pragma omp parallel for
for(int i=0; i<n; i++)
visited[i] = false;
int v;
queue<int> bfsq;
if(!visited[s])
{
cout<<arr[s]<<" ";
#pragma omp critical
bfsq.push(s);
visited[s] = true;
while(!bfsq.empty())
{
v = bfsq.front();
#pragma omp parallel for
for(int i=0; i<n; i++)
{
if(adj_mat[v][i] && !visited[i])
{
cout<<arr[i]<<" ";
visited[i] = true;
bfsq.push(i);
}
}
#pragma omp critical
bfsq.pop();
}
}
}
int main
()
{
cout<<"Enter no. of cities: ";
int n, u;
cin>>n;
string cities[n];
for(int i=0; i<n; i++)
{
cout<<"Enter city #"<<i<<" (Airport Code): ";
cin>>cities[i];
}
cout<<"\nYour cities are: "<<endl;
for(int i=0; i<n; i++)
cout<<"city #"<<i<<": "<<cities[i]<<endl;
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
cout<<"Enter distance between "<<cities[i]<<" and "<<cities[j]<<": ";
cin>>adj_mat[i][j];
adj_mat[j][i] = adj_mat[i][j];
}
}
cout<<endl;
for(int i=0; i<n; i++)
cout<<"\t"<<cities[i]<<"\t";
for(int i=0; i<n; i++)
{
cout<<"\n"<<cities[i];
for(int j=0; j<n; j++)
cout<<"\t"<<adj_mat[i][j]<<"\t";
cout<<endl;
}
cout<<"Enter Starting Vertex: ";
cin>>u;
cout<<"BFS: "<<endl;
bfs(u,n,cities);
return 0;
}