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.

AdvancedAdvanced graphsGraph optimization

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 0 1 1 1

COMPLETE C PROGRAM

Complete C implementation

ads-zero-one-bfs.c
Open in compiler
#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;
}

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 0 1 1 1
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Push zero-weight relaxations to the deque front and one-weight relaxations to its back.
  3. 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.