-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.cpp
More file actions
81 lines (75 loc) · 1.57 KB
/
BFS.cpp
File metadata and controls
81 lines (75 loc) · 1.57 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include<iostream>
#include<vector>
#include<queue>
#include<iterator>
using namespace std;
class Graph
{
public:
int size;
int **adjmatrix;
int *visited;
vector<int>bfsOrder;
Graph(int n): size(n)
{
adjmatrix=new int*[size];
for(int i=0;i<size;i++)
adjmatrix[i]=new int[size];
visited=new int[size];
cout<<"Enter the adjacency matrix\n";
for(int i=0;i<size;i++)
{
for(int j=0;j<size;j++)
cin>>adjmatrix[i][j];
visited[i]=0;
}
}
void bfs(Graph&);
void bfsHelp(Graph&, int);
void display(Graph&);
};
void Graph::bfs(Graph& gr)
{
for(int i=0;i<gr.size;i++)
if(gr.visited[i]==0)
bfsHelp(gr,i);
}
void Graph::bfsHelp(Graph& gr,int i)
{
queue<int>bfsqueue;
gr.visited[i]=1;
bfsqueue.push(i);
int rowIndex;
while(!bfsqueue.empty())
{
rowIndex=bfsqueue.front();
for(int k=0;k<gr.size;k++)
{
if(gr.adjmatrix[rowIndex][k]==1 && gr.visited[k]==0)
{
gr.visited[k]=1;
bfsqueue.push(k);
}
}
bfsOrder.push_back(bfsqueue.front());
bfsqueue.pop();
}
}
void Graph::display(Graph& gr)
{
vector<int>::iterator i;
for(i=gr.bfsOrder.begin();i!=gr.bfsOrder.end();i++)
cout<<*i<<" ";
cout<<endl;
}
int main()
{
int n;
cout<<"Enter the size of adj matrix(m=n)\n";
cin>>n;
Graph graph(n);
graph.bfs(graph);
cout<<"BFS order: \n";
graph.display(graph);
return 0;
}