0
0
DSA Typescriptprogramming~30 mins

Graph Terminology Vertices Edges Directed Undirected Weighted in DSA Typescript - Build from Scratch

Choose your learning style9 modes available
Graph Terminology: Vertices, Edges, Directed, Undirected, Weighted
📖 Scenario: Imagine you are creating a simple map of cities connected by roads. Each city is a point (vertex), and each road is a connection (edge) between cities. Some roads have directions (one-way), and some have distances (weights).
🎯 Goal: You will build a basic graph using TypeScript objects to represent cities and roads. You will mark if roads are one-way or two-way and add distances to roads.
📋 What You'll Learn
Create a graph object with cities as keys and arrays of connected cities as values
Add a configuration variable to mark if the graph is directed or undirected
Add weights (distances) to the edges
Print the graph connections with directions and weights
💡 Why This Matters
🌍 Real World
Graphs are used to model maps, social networks, computer networks, and many other connections in real life.
💼 Career
Understanding graph basics is important for software developers working on navigation apps, recommendation systems, and network analysis.
Progress0 / 4 steps
1
Create the graph with cities and roads
Create a variable called graph as an object with these exact entries: 'A': ['B', 'C'], 'B': ['C'], 'C': ['A']
DSA Typescript
Hint

Use an object where keys are city names and values are arrays of connected cities.

2
Add a variable to mark if the graph is directed
Create a boolean variable called isDirected and set it to true
DSA Typescript
Hint

This variable will help us know if roads have directions or not.

3
Add weights (distances) to the edges
Create a variable called weightedGraph as an object where each city key maps to an array of objects with node and weight properties. Use these exact entries: 'A': [{ node: 'B', weight: 5 }, { node: 'C', weight: 10 }], 'B': [{ node: 'C', weight: 3 }], 'C': [{ node: 'A', weight: 1 }]
DSA Typescript
Hint

Use an object with arrays of objects to store connected nodes and their distances.

4
Print the graph connections with directions and weights
Use a for loop with variables city and edges to iterate over Object.entries(weightedGraph). Inside the loop, use another for loop with variables edge to iterate over edges. Print each connection in this exact format: "City A -> City B (Distance: 5)" using console.log
DSA Typescript
Hint

Use nested loops to print each road with its distance.