File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ // written by hg398
2
+
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+ vector <int > adj[100000 ]; // vector to implement graph using adjacency lists (size can vary a/c to need)
6
+ bool mark[100000 ]; // array to keep record of visited nodes
7
+ void bfs (int s)
8
+ {
9
+ queue <int > q; // Create a queue for BFS
10
+ mark[s] = true ; // Mark the current node as visited and enqueue it
11
+ q.push (s);
12
+
13
+ while (!q.empty ())
14
+ {
15
+ s = q.front (); // Dequeue a vertex from queue and print it
16
+ cout << s+1 << " " ;
17
+ q.pop ();
18
+
19
+ // Get all adjacent vertices of the dequeued vertex s
20
+ // If a adjacent has not been visited, then mark it visited
21
+ // and enqueue it
22
+ for (int i = 0 ; i < adj[s].size (); ++i)
23
+ {
24
+ if (!mark[adj[s][i]])
25
+ {
26
+ mark[adj[s][i]] = true ;
27
+ q.push (adj[s][i]);
28
+ }
29
+ }
30
+ }
31
+ }
32
+
33
+ int main () {
34
+ int nodes,edges; // no. of nodes and edges in graph
35
+ cin>>nodes>>edges;
36
+ while (edges--)
37
+ {
38
+ int a,b; // vertices between which an edge exist
39
+ cin>>a>>b;
40
+ a--;b--; // 0-based indexing
41
+ adj[a].push_back (b); // adding b to adjacency list of a to which it is directly connected
42
+ adj[b].push_back (a); // adding a to adjacency list of b to which it is directly connected
43
+ }
44
+ memset (mark,false ,sizeof (mark)); // marking all vertices unvisited
45
+ int source; // source node
46
+ cin>>source;
47
+ bfs (source);
48
+ return 0 ;
49
+ }
You can’t perform that action at this time.
0 commit comments