-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBFS.cpp
50 lines (43 loc) · 934 Bytes
/
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
#include <iostream> // Adj Matrix
#include <vector>
#include <queue>
using namespace std;
void BFS(int n , vector<vector<int>> G , int v)
{
int visited[n],i;
memset(visited, 0, sizeof(visited));
queue<int> q;
q.push(v);
cout<<"\nVisit\t"<<v;
visited[v]=1;
while(!q.empty())
{
v = q.front();
for(i=0 ; i<n;i++)
{
if(!visited[i] && G[v][i] != 0)
{
q.push(i);
visited[i]=1;
cout<<"\nVisit\t"<<i;
}
}
q.pop();
}
cout<<endl;
}
int main()
{
int n;
int startNode;
cout<<"Enter number of vertices"<<endl;
cin>>n;
vector<vector<int>> G( n , vector<int>(n));
for(int i=0 ; i<n; i++)
for(int j=0 ; j<n ; j++)
cin>>G[i][j];
cout<<"Enter Starting Node"<<endl;
cin>>startNode;
BFS(n , G , startNode);
return 0;
}