You are on page 1of 11

Assignment #2

1. Shortest path of Directed Acyclic Graph (DAG)

Date of Performance: 03/01/2022 Student ID: 190204055

Date of Submission: 17/01/2022 Name: Jannatim Maisha

Group: A2
Question:
Write a code for finding all the shortest path from single source to all nodes on a DAG using
Topological Sort.

CODE:
#include<bits/stdc++.h>

using namespace std;

#define INF INT_MAX

vector<pair<int,int>>gr[200];

bool visited[200];

stack<int>rst;

vector<int>dis;
void DFS(int src)

visited[src]=1;

for(int i=0; i<gr[src].size(); i++)

int neig=gr[src][i].first;

if(visited[neig]==0)

{
DFS(neig);

rst.push(src);

void shortestPath(int src, int N)

{
int dist[N];

for (int i = 0; i < N; i++)

dist[i] = 1e9;

dist[src] = 0;

while(!rst.empty())

int node = rst.top();

rst.pop();
if (dist[node] != INF) {

for(auto it : gr[node]) {

if(dist[node] + it.second < dist[it.first]) {

dist[it.first] = dist[node] + it.second;

for (int i = 0; i < N; i++)


(dist[i] == 1e9)? cout << "INF ": cout << dist[i] << " ";

void print(stack<int>stk)

while(!stk.empty())

int x = stk.top();

stk.pop();

cout << x << ' ';

}
cout << endl;

int main()

int n,m;

cin>>n>>m;

int s;

cin>>s;
for(int i=0; i<m; i++)

int x,y,w;

cin>>x>>y>>w;

gr[x].push_back({y,w});

for(int i=1; i<=n; i++)

if(visited[i]==0)
DFS(i);

cout<<"topologically sorted order->";

print(rst);

shortestPath(s,n);
}

You might also like