0
0
DSA Typescriptprogramming~30 mins

Shortest Path in DAG Using Topological Order in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Shortest Path in DAG Using Topological Order
📖 Scenario: You are working on a project to find the shortest travel time between cities connected by one-way roads. The roads form a network without any loops, so the map is a Directed Acyclic Graph (DAG). You want to find the quickest route from the starting city to all other cities.
🎯 Goal: Build a TypeScript program that finds the shortest path distances from a starting city to all other cities in a DAG using topological order.
📋 What You'll Learn
Create a graph as an adjacency list with exact edges and weights
Create a variable for the number of cities
Implement topological sorting using DFS
Calculate shortest paths using the topological order
Print the shortest distances array
💡 Why This Matters
🌍 Real World
Finding shortest paths in a DAG is useful in project scheduling, task ordering, and routing where cycles do not exist.
💼 Career
Understanding shortest path algorithms and topological sorting is important for software engineers working on compilers, network routing, and dependency resolution.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a variable called graph as an adjacency list representing the following directed edges with weights:
0 -> 1 (5), 0 -> 2 (3), 1 -> 3 (6), 1 -> 2 (2), 2 -> 4 (4), 2 -> 5 (2), 2 -> 3 (7), 3 -> 4 (-1), 4 -> 5 (-2).
Use an array of arrays where each inner array contains tuples of [neighbor, weight].
DSA Typescript
Hint

Represent the graph as an array where each index is a city and contains a list of pairs [neighbor, weight].

2
Create the number of cities variable
Create a variable called numCities and set it to the number of cities in the graph.
DSA Typescript
Hint

Use the length property of the graph array to get the number of cities.

3
Implement topological sort and shortest path calculation
Write a function called topologicalSort that takes graph and numCities and returns an array with the topological order of the cities. Then create a function called shortestPathDAG that takes graph, numCities, and a starting city start, and returns an array of shortest distances from start to all cities using the topological order. Use Infinity for unreachable cities.
DSA Typescript
Hint

Use DFS to get topological order. Then relax edges in that order to find shortest paths.

4
Print the shortest distances from city 1
Call the function shortestPathDAG with graph, numCities, and starting city 1. Then print the returned array of shortest distances.
DSA Typescript
Hint

Call shortestPathDAG with start city 1 and print the result array.