#include <stdio.h>
#include <stdlib.h>
#define MAX 5
// Node for adjacency list
typedef struct Node {
int vertex;
struct Node* next;
} Node;
// Graph structure
typedef struct Graph {
Node* adjLists[MAX];
int visited[MAX];
int distance[MAX];
} Graph;
// Create node
Node* createNode(int v) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
// Initialize graph
void initGraph(Graph* graph) {
for (int i = 0; i < MAX; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
graph->distance[i] = -1; // -1 means unvisited
}
}
// Add edge
void addEdge(Graph* graph, int src, int dest) {
Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
// BFS to find shortest path distance
void bfsShortestPath(Graph* graph, int start, int target) {
int queue[MAX];
int front = 0, rear = 0;
graph->visited[start] = 1;
graph->distance[start] = 0;
queue[rear++] = start;
while (front < rear) {
int current = queue[front++]; // dequeue
if (current == target) {
break; // reached target
}
Node* temp = graph->adjLists[current];
while (temp) {
int adjVertex = temp->vertex;
if (!graph->visited[adjVertex]) {
graph->visited[adjVertex] = 1;
graph->distance[adjVertex] = graph->distance[current] + 1;
queue[rear++] = adjVertex; // enqueue
}
temp = temp->next;
}
}
printf("Shortest distance from %d to %d is %d\n", start, target, graph->distance[target]);
}
int main() {
Graph graph;
initGraph(&graph);
addEdge(&graph, 0, 1);
addEdge(&graph, 0, 2);
addEdge(&graph, 1, 3);
addEdge(&graph, 2, 3);
addEdge(&graph, 3, 4);
bfsShortestPath(&graph, 0, 4);
return 0;
}graph->visited[start] = 1;
graph->distance[start] = 0;
queue[rear++] = start;
Initialize BFS from start node with distance zero and enqueue it
int current = queue[front++];
Dequeue current node to explore neighbors
if (current == target) { break; }
Stop BFS when target node is reached
while (temp) { int adjVertex = temp->vertex; if (!graph->visited[adjVertex]) { graph->visited[adjVertex] = 1; graph->distance[adjVertex] = graph->distance[current] + 1; queue[rear++] = adjVertex; } temp = temp->next; }
Visit all unvisited neighbors, update distance, and enqueue them
printf("Shortest distance from %d to %d is %d\n", start, target, graph->distance[target]);
Print the shortest distance found
Shortest distance from 0 to 4 is 3