Experiment 8
Experiment 8
8
Objective: To implement BFS using linked list.
Theory: The Breadth First Search (BFS) traversal is an algorithm, which is used to
visit all of the nodes of a given graph. In this traversal algorithm one node is
selected and then all of the adjacent nodes are visited one by one. After
completing all of the adjacent vertices, it moves further to check another vertices
and checks its adjacent vertices again. This process will continue until all nodes
are visited.
According to BFS traversal method, first step is to visit any vertex, so we have
visited 1. Next step is to explore that visited vertex, that means we have to visit
adjacent vertex of 1, so we have visited 2,3 and 5. Again we have to visit any
unvisited vertex, so we have visited 4.
Algorithm:
1. Initialization:
1.1. Create an empty adjacency list adjList with size equal to the number of
vertices.
1.2. For each vertex, initialize its adjacency list as empty.
2. Add Edges:
2.1. For each edge (u, v) in edges[], do the following:
2.2. Create a new node with value v.
2.3. Insert this new node at the beginning of the adjacency list of vertex u.
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Number of vertices in the graph
int vertices = 5;
// Adjacency list representation of the graph
struct Node* adjList[vertices];
for (int i = 0; i < vertices; ++i)
adjList[i] = NULL;
// Add edges to the graph
addEdge(adjList, 0, 1);
addEdge(adjList, 0, 2);
addEdge(adjList, 1, 3);
addEdge(adjList, 1, 4);
addEdge(adjList, 2, 4);
// Mark all the vertices as not visited
int visited[vertices];
for (int i = 0; i < vertices; ++i)
visited[i] = 0;
// Perform BFS traversal starting from vertex 0
printf(
"Breadth First Traversal starting from vertex 0: ");
bfs(adjList, vertices, 0, visited);
return 0;
}
Output:
Breadth First Traversal starting from vertex 0: 0 2 1 4 3