
About the author
Mallikarjuna Mallisetty
General programming
Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.
View LinkedIn profile ↗#include <stdio.h>
#include <stdlib.h>
#define MAX 1000
int queue[MAX], front = 0, rear = 0;
void enqueue(int val) {
queue[rear++] = val;
}
int dequeue() {
return queue[front++];
}
int isEmpty() {
return front == rear;
}
int main() {
int n = 4;
int edges[][2] = {{0,1},{0,2},{1,3}};
int m = sizeof(edges)/sizeof(edges[0]);
int graph[MAX][MAX] = {0};
int degree[MAX] = {0};
int distance[MAX];
for (int i = 0; i < m; i++) {
int u = edges[i][0], v = edges[i][1];
graph[u][degree[u]++] = v;
graph[v][degree[v]++] = u;
}
for (int i = 0; i < n; i++) distance[i] = -1;
distance[0] = 0;
enqueue(0);
while (!isEmpty()) {
int current = dequeue();
for (int i = 0; i < degree[current]; i++) {
int neighbor = graph[current][i];
if (distance[neighbor] == -1) {
distance[neighbor] = distance[current] + 1;
enqueue(neighbor);
}
}
}
for (int i = 0; i < n; i++) {
printf("%d ", distance[i]);
}
printf("\n");
return 0;
}