Javatpoint Logo
Javatpoint Logo

BFS Program in C

BFS (breadth-first search) is an algorithm that is used for traversing or searching a graph or tree data structure. It starts at the root node (or any arbitrary node) and explores all the nodes at the current depth level before moving on to the nodes at the next depth level.

The algorithm uses a queue to keep track of which vertices to visit next. It starts by adding the root vertex to the queue and then repeatedly removes vertices from the front of the queue, adds their neighbors to the back of the queue, and marks them as visited. This process continues until the queue is empty, indicating that all reachable vertices have been visited.


Sample code to implement the BFS algorithm:


BFS traversal starting from vertex 0: 0 2 1 4 3 5

Similarly, when you run the code with the initial vertex as 1 the output would be:

BFS traversal starting from vertex 1: 1 4 3 0 5 2


This code creates a graph with 6 vertices and adds edges between them. After that, it performs a BFS traversal of the graph starting from vertex 0 and prints the order in which the vertices are visited. In this code, the 'struct node' represents a node in the adjacency list, 'struct adj_list' represents the adjacency list, and 'struct graph' represents the entire graph. The 'create_graph' function creates a new graph with 'n' vertices, and the 'add_edge' function adds an edge between two vertices.

The 'bfs' function implements the BFS algorithm, starting from the vertex 'v'. A queue and a visited array are used to keep track of which vertices should be visited next. The 'main' function creates a graph and adds some edges, and then calls the 'bfs' function starting from vertex 0.

The time and space complexities of this BFS algorithm can be discussed as follows:

Time complexity:

  • This algorithm has an O(V+E) time complexity, where V is the number of graph vertices and E is the number of graph edges.
  • In the worst case, we need to visit all the vertices and edges in the graph, so the time complexity is proportional to the size of the graph.

Space complexity:

  • The BFS algorithm has an O(V) space complexity, where V is the number of graph vertices. It is because we need to store the visited vertices and the vertices in the queue.
  • In the worst case, all vertices can be added to the queue, so the space complexity is proportional to the size of the graph.

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA