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.

IntermediateBFSQueueVisited

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 1 2 3 4

COMPLETE C PROGRAM

Complete C implementation

dsa-graph-breadth-first-search.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

0 1 2 3 4
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Mark vertices when they enter the queue so each vertex is processed once.
  3. 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.