ADVANCED DATA STRUCTURES PROGRAM • LEVEL 20 — ADVANCED GRAPH ALGORITHMS
Find Shortest Paths with 0–1 BFS
Learn how to find shortest paths with 0–1 bfs using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
0 0 1 1 1
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int graph[5][5]={{0,0,-1,-1,1},{0,0,1,-1,-1},{-1,1,0,0,-1},{-1,-1,0,0,1},{1,-1,-1,1,0}};
int distance[5]={0,99,99,99,99},deque[20],front=10,back=10;deque[back++]=0;
while(front<back){int node=deque[front++];for(int next=0;next<5;next++)if(graph[node][next]>=0&&node!=next){int weight=graph[node][next];if(distance[node]+weight<distance[next]){distance[next]=distance[node]+weight;if(weight==0)deque[--front]=next;else deque[back++]=next;}}}
for(int i=0;i<5;i++){printf("%d%c",distance[i],i==4?'\n':' ');}
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 0 1 1 1
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Push zero-weight relaxations to the deque front and one-weight relaxations to its back.
- Display the computed result.
Push zero-weight relaxations to the deque front and one-weight relaxations to its back.
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.
