-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs_example.cpp
More file actions
100 lines (84 loc) · 2.16 KB
/
Copy pathbfs_example.cpp
File metadata and controls
100 lines (84 loc) · 2.16 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Breadth-first-search (BFS) from a given vertex in a graph.
*/
#include<iostream>
#include <list>
using std::cout;
using std::list;
class Graph
{
int N; // number of vertices
list<int> *adj; // pointer to array of adjacency lists
public:
Graph(int N); // create a Graph with N vertices
void addEdge(int n, int w); // add an edge between two vertices
void BFS(int s); // BFS traversal from source vertex s
};
Graph::Graph(int N) {
this->N = N;
adj = new list<int>[N];
}
void Graph::addEdge(int n, int w) {
adj[n].push_back(w);
}
void Graph::BFS(int s) {
// initially all the vertices are set to not-visited
bool *visited = new bool[N];
for(int i = 0; i < N; i++)
visited[i] = false;
// create a queue for BFS
list<int> queue;
// set the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
// iterator used to get all adjacent vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued vertex s.
// If an adjacent vertex has not been visited, then mark
// it visited and enqueue it.
for (i = adj[s].begin(); i != adj[s].end(); ++i) {
if (!visited[*i]) {
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
int main()
{
// Create a graph
Graph g(24);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(1,4);
g.addEdge(2,0);
g.addEdge(2,1);
g.addEdge(2,3);
g.addEdge(2,4);
g.addEdge(2,5);
g.addEdge(3,2);
g.addEdge(3,4);
g.addEdge(3,6);
g.addEdge(4,1);
g.addEdge(4,2);
g.addEdge(4,3);
g.addEdge(5,2);
g.addEdge(5,6);
g.addEdge(6,3);
g.addEdge(6,5);
g.addEdge(6,7);
g.addEdge(7,4);
g.addEdge(7,6);
g.addEdge(7,8);
g.addEdge(8,7);
cout << "Breadth First Traversal (starting from vertex 3) \n";
g.BFS(3);
return 0;
}