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: