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.
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
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
0 5 3 10 7 5
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Relax outgoing edges once in topological order, which works even with negative weights in a DAG.
- 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.
