-
Notifications
You must be signed in to change notification settings - Fork 254
/
Copy path07 Breadth First Search Using STLQueue.cpp
49 lines (39 loc) · 1.22 KB
/
07 Breadth First Search Using STLQueue.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
#include <iostream>
#include <queue>
using namespace std;
void BFS(int vtx, int A[][8], int n){
queue<int> Q;
int visited[8] {0};
// Initial
cout << vtx << ", " << flush; // Visit vertex
visited[vtx] = 1;
Q.emplace(vtx);
// Explore
while (!Q.empty()){
int u = Q.front(); // Vertex u for exploring
Q.pop();
for (int v=1; v<=n; v++){ // Adjacent vertices of vertex u
if (A[u][v] == 1 && visited[v] == 0){ // Adjacent vertex and not visited
cout << v << ", " << flush; // Visit vertex
visited[v] = 1;
Q.emplace(v);
}
}
}
cout << endl;
}
int main (){
int A[8][8] = {{0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 1, 1, 1, 0, 0, 0},
{0, 1, 0, 1, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 1, 0, 0},
{0, 1, 0, 1, 0, 1, 0, 0},
{0, 0, 0, 1, 1, 0, 1, 1},
{0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0}};
cout << "Vertex: 1 -> " << flush;
BFS(1, A, 8);
cout << "Vertex: 4 -> " << flush;
BFS(4, A, 8);
return 0;
}