DATA STRUCTURES PROGRAM • GRAPHS
Traverse a Graph with Breadth-First Search
Learn how to traverse a graph with breadth-first search using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 2 3 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int graph[5][5] = {
{0,1,1,0,0}, {1,0,0,1,0}, {1,0,0,1,1}, {0,1,1,0,0}, {0,0,1,0,0}
};
int visited[5] = {0}, queue[5], front = 0, rear = 0;
visited[0] = 1; queue[rear++] = 0;
while (front < rear) {
int vertex = queue[front++];
printf("%d ", vertex);
for (int neighbour = 0; neighbour < 5; neighbour++)
if (graph[vertex][neighbour] && !visited[neighbour]) {
visited[neighbour] = 1; queue[rear++] = neighbour;
}
}
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 2 3 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Mark vertices when they enter the queue so each vertex is processed once.
- Display the computed result.
Mark vertices when they enter the queue so each vertex is processed once.
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.
