ADVANCED DATA STRUCTURES PROGRAM • LEVEL 20 — ADVANCED GRAPH ALGORITHMS

Find Shortest Paths in a Weighted DAG

Learn how to find shortest paths in a weighted dag using a clear C program.

AdvancedAdvanced graphsGraph optimization

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
0 5 3 10 7 5

COMPLETE C PROGRAM

Complete C implementation

ads-dag-shortest-path.c
Open in compiler
#include <stdio.h>

int main(void)
{
    int weight[6][6]={{0,5,3,0,0,0},{0,0,2,6,0,0},{0,0,0,7,4,2},{0,0,0,0,-1,1},{0,0,0,0,0,-2},{0,0,0,0,0,0}},order[]={0,1,2,3,4,5},distance[]={0,99,99,99,99,99};
    for(int p=0;p<6;p++){int node=order[p];for(int next=0;next<6;next++)if(weight[node][next]&&distance[node]+weight[node][next]<distance[next])distance[next]=distance[node]+weight[node][next];}
    for(int i=0;i<6;i++){printf("%d%c",distance[i],i==5?'\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 5 3 10 7 5
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Relax outgoing edges once in topological order, which works even with negative weights in a DAG.
  3. Display the computed result.

Relax outgoing edges once in topological order, which works even with negative weights in a DAG.

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.