ADVANCED DATA STRUCTURES PROGRAM • LEVEL 20 — ADVANCED GRAPH ALGORITHMS
Construct an Eulerian Circuit with Hierholzer's Algorithm
Learn how to construct an eulerian circuit with hierholzer's algorithm using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 1 2 3 4 2 0
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int graph[5][5]={{0,1,1,0,0},{1,0,1,0,0},{1,1,0,1,1},{0,0,1,0,1},{0,0,1,1,0}},stack[20],circuit[20],top=0,count=0;stack[top++]=0;
while(top){int node=stack[top-1],next=-1;for(int i=0;i<5;i++)if(graph[node][i]){next=i;break;}if(next>=0){graph[node][next]=graph[next][node]=0;stack[top++]=next;}else circuit[count++]=stack[--top];}
for(int i=count-1;i>=0;i--){printf("%d%c",circuit[i],i?' ':'\n');}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 1 2 3 4 2 0
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Follow unused edges on a stack and append a vertex only when it has no remaining edge.
- Display the computed result.
Follow unused edges on a stack and append a vertex only when it has no remaining edge.
EFFICIENCY
Time and space complexity
Time complexity
O(V + E)
Auxiliary space
O(V + E)
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.
