BFS Simplest C++ ๐Ÿ’ช

Aashish Budania
2 min readJun 23, 2020

--

Hello!

Letโ€™s learn one of the best algorithm named as BFS ๐Ÿ‘ผ๐Ÿป.

It uses a queue to traverse the graphโ€™s nodes. The source node is added to queue and then we start with condition until queue is empty ๐Ÿ˜Ž.

So we start popping out the node from the queue until its empty and we also push the non-visited adjacent nodes to the queue of the current nodeโœŒ๏ธ.

To maintain the state of nodes whether they are visited or not we use an array named visited [โœ๏ธ].

Now letโ€™s have a look at the source code in c++ for the same ๐Ÿ’ป.

BFS Algorithm Simplest ๐Ÿ˜‡

The above code is very easy to understand and implement ๐Ÿ™ƒ. I have added the picture over here, so you would love to code instead of copy ๐Ÿ˜œ ๐Ÿ˜œ.

Itโ€™s too easy and you can code it in one go, so the above function takes three arguments as soucre vertex named as start, number of vertices and the adjacency list of the all graph nodes. ๐Ÿค—

To understant the input see the below screenshot-

Fig : Reading inputs for graph

Cheers!! ๐Ÿ‘Š

Thank you for reading!๐Ÿ“–

Clap if you like it ๐Ÿ‘๐Ÿ‘

--

--

Aashish Budania

Backend Engineer at Karza Technologies Pvt Ltd | NITK Surathkal, Karnataka