DATA STRUCTURES PROGRAM • GRAPHS
Find Unweighted Shortest-Path Distances with BFS
Learn how to find unweighted shortest-path distances with bfs using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 1 2 2 3
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int graph[6][6] = {
{0,1,1,0,0,0}, {1,0,0,1,0,0}, {1,0,0,1,1,0},
{0,1,1,0,0,1}, {0,0,1,0,0,1}, {0,0,0,1,1,0}
};
int distance[6] = {-1,-1,-1,-1,-1,-1}, queue[6], front = 0, rear = 0;
distance[0] = 0; queue[rear++] = 0;
while (front < rear) {
int vertex = queue[front++];
for (int neighbour = 0; neighbour < 6; neighbour++)
if (graph[vertex][neighbour] && distance[neighbour] < 0) {
distance[neighbour] = distance[vertex] + 1; queue[rear++] = neighbour;
}
}
for (int vertex = 0; vertex < 6; vertex++) printf("%d ", distance[vertex]);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 1 2 2 3
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- The first BFS discovery gives the minimum edge count from the source.
- Display the computed result.
The first BFS discovery gives the minimum edge count from the source.
EFFICIENCY
Time and space complexity
Time complexity
O(V²) with matrix
Auxiliary space
O(V)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
