0
0
DSA Typescriptprogramming~30 mins

Shortest Path in Unweighted Graph Using BFS in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Shortest Path in Unweighted Graph Using BFS
📖 Scenario: Imagine you are navigating a city with intersections connected by roads. You want to find the shortest number of roads to travel from one intersection to another.
🎯 Goal: You will build a program that finds the shortest path length between two intersections in an unweighted graph using Breadth-First Search (BFS).
📋 What You'll Learn
Create a graph as an adjacency list with exact nodes and edges
Set up start and end nodes for the path search
Implement BFS to find the shortest path length
Print the shortest path length or -1 if no path exists
💡 Why This Matters
🌍 Real World
Finding shortest routes in maps, social networks, or network routing where all connections have equal cost.
💼 Career
Understanding BFS and shortest path algorithms is essential for software engineers working on navigation, recommendation systems, and network analysis.
Progress0 / 4 steps
1
Create the graph as an adjacency list
Create a variable called graph as a Map<string, string[]> with these exact entries: 'A' connected to ['B', 'C'], 'B' connected to ['A', 'D', 'E'], 'C' connected to ['A', 'F'], 'D' connected to ['B'], 'E' connected to ['B', 'F'], and 'F' connected to ['C', 'E'].
DSA Typescript
Hint

Use new Map() with an array of key-value pairs where keys are node names and values are arrays of connected nodes.

2
Set start and end nodes
Create two variables: start set to 'A' and end set to 'F'.
DSA Typescript
Hint

Just create two string variables with the exact names and values.

3
Implement BFS to find shortest path length
Write a function called shortestPathLength that takes graph, start, and end as parameters and returns the shortest path length as a number. Use a queue for BFS, a Set called visited to track visited nodes, and a Map called distance to store distances from start. Return -1 if end is not reachable.
DSA Typescript
Hint

Use a queue to explore nodes level by level. Track visited nodes to avoid repeats. Store distance from start for each node. Return distance when you reach the end.

4
Print the shortest path length
Call shortestPathLength(graph, start, end) and print the result using console.log.
DSA Typescript
Hint

Call the function with the graph, start, and end nodes, then print the returned number.