DATA STRUCTURES PROGRAM • GRAPHS
Traverse a Graph with Depth-First Search
Learn how to traverse a graph with depth-first search using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 3 2 4
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void dfs(int vertex, int graph[5][5], int visited[5])
{
visited[vertex] = 1; printf("%d ", vertex);
for (int neighbour = 0; neighbour < 5; neighbour++)
if (graph[vertex][neighbour] && !visited[neighbour]) dfs(neighbour, graph, visited);
}
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};
dfs(0, graph, visited);
putchar('\n');
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 3 2 4
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Recursively finish each unvisited neighbour branch before trying the next one.
- Display the computed result.
Recursively finish each unvisited neighbour branch before trying the next one.
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.
