#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_NODES 5
// Graph represented as adjacency matrix
int graph[MAX_NODES][MAX_NODES] = {
{0, 0, 0, 0, 0}, // Node 0 unused
{0, 0, 1, 1, 0}, // 1->2, 1->3
{0, 0, 0, 1, 0}, // 2->3
{0, 0, 0, 0, 1}, // 3->4
{0, 1, 0, 0, 0} // 4->1
};
// Simple queue for BFS
typedef struct {
int items[MAX_NODES];
int front, rear;
} Queue;
void enqueue(Queue* q, int val) {
q->items[++q->rear] = val;
}
int dequeue(Queue* q) {
return q->items[++q->front];
}
bool isEmpty(Queue* q) {
return q->front == q->rear;
}
void shortestPath(int start, int end) {
bool visited[MAX_NODES] = {false};
int parent[MAX_NODES];
for (int i = 0; i < MAX_NODES; i++) parent[i] = -1;
Queue q = {.front = -1, .rear = -1};
enqueue(&q, start);
visited[start] = true;
while (!isEmpty(&q)) {
int current = dequeue(&q); // advance current node
if (current == end) break; // stop if destination reached
for (int i = 1; i < MAX_NODES; i++) {
if (graph[current][i] && !visited[i]) {
enqueue(&q, i); // enqueue neighbors
visited[i] = true; // mark visited
parent[i] = current; // track path
}
}
}
// Reconstruct path
if (!visited[end]) {
printf("No path found from %d to %d\n", start, end);
return;
}
int path[MAX_NODES];
int count = 0;
for (int v = end; v != -1; v = parent[v]) {
path[count++] = v; // build path backwards
}
printf("Shortest path from %d to %d: ", start, end);
for (int i = count - 1; i >= 0; i--) {
printf("%d", path[i]);
if (i > 0) printf(" -> ");
}
printf("\n");
}
int main() {
shortestPath(1, 4);
return 0;
}
int current = dequeue(&q);
advance current node from queue to explore neighbors
if (current == end) break;
stop search when destination node is reached
if (graph[current][i] && !visited[i]) { enqueue(&q, i); visited[i] = true; parent[i] = current; }
enqueue unvisited neighbors and track their parent for path reconstruction
for (int v = end; v != -1; v = parent[v]) { path[count++] = v; }
reconstruct path by following parent links backwards from destination
Shortest path from 1 to 4: 1 -> 3 -> 4