File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change 1+
2+
3+ #include < iostream>
4+ #include < list>
5+
6+ using namespace std ;
7+
8+
9+ class Graph
10+ {
11+ int V;
12+
13+
14+ list<int > *adj;
15+ public:
16+ Graph (int V);
17+
18+
19+ void addEdge (int v, int w);
20+
21+
22+ void BFS (int s);
23+ };
24+
25+ Graph::Graph (int V)
26+ {
27+ this ->V = V;
28+ adj = new list<int >[V];
29+ }
30+
31+ void Graph::addEdge (int v, int w)
32+ {
33+ adj[v].push_back (w);
34+ }
35+
36+ void Graph::BFS (int s)
37+ {
38+
39+ bool *visited = new bool [V];
40+ for (int i = 0 ; i < V; i++)
41+ visited[i] = false ;
42+
43+ list<int > queue;
44+
45+ visited[s] = true ;
46+ queue.push_back (s);
47+
48+
49+ list<int >::iterator i;
50+
51+ while (!queue.empty ())
52+ {
53+
54+ s = queue.front ();
55+ cout << s << " " ;
56+ queue.pop_front ();
57+
58+
59+ for (i = adj[s].begin (); i != adj[s].end (); ++i)
60+ {
61+ if (!visited[*i])
62+ {
63+ visited[*i] = true ;
64+ queue.push_back (*i);
65+ }
66+ }
67+ }
68+ }
69+
70+ // Driver program to test methods of graph class
71+ int main ()
72+ {
73+
74+ Graph g (4 );
75+ g.addEdge (0 , 1 );
76+ g.addEdge (0 , 2 );
77+ g.addEdge (1 , 2 );
78+ g.addEdge (2 , 0 );
79+ g.addEdge (2 , 3 );
80+ g.addEdge (3 , 3 );
81+
82+ cout << " Breadth First Traversal "
83+ << " (starting from vertex 0) \n " ;
84+ g.BFS (0 );
85+
86+ return 0 ;
87+ }
You can’t perform that action at this time.
0 commit comments