📖 Scenario: Imagine you are organizing a city's road map. Roads connect different places, and some places have multiple roads leading to others. You want to represent this map in your program.Trees are like family trees or company hierarchies where each child has only one parent. But city roads can loop back or connect in many ways, which trees cannot show well.
🎯 Goal: Build a simple graph using a dictionary to show connections between places. Understand why trees cannot model all connections like roads that loop or connect multiple ways.
📋 What You'll Learn
Create a dictionary called cityMap with places as keys and lists of connected places as values
Add a variable called startPlace to pick a place to explore connections from
Write a loop to print all places connected directly to startPlace
Print the connected places clearly to show the graph structure
💡 Why This Matters
🌍 Real World
Graphs are used to model complex networks like city roads, social networks, and internet connections where multiple connections and loops exist.
💼 Career
Understanding graphs helps in software development roles involving network analysis, route planning, recommendation systems, and more.
Progress0 / 4 steps
1
Create the city map graph
Create a dictionary called cityMap with these exact entries: "Park" connected to ["Museum", "Library"], "Museum" connected to ["Park", "Cafe"], "Library" connected to ["Park"], and "Cafe" connected to ["Museum"].
DSA C#
Hint
Use a Dictionary<string, List<string>> to represent places and their connected places.
2
Set the starting place
Add a string variable called startPlace and set it to "Park".
DSA C#
Hint
Just create a string variable startPlace and assign it the value "Park".
3
Print connected places from the start
Write a foreach loop using place to iterate over cityMap[startPlace] and print each connected place.
DSA C#
Hint
Use foreach (string place in cityMap[startPlace]) to loop and Console.WriteLine(place) to print.
4
Display the connected places clearly
Print a line before the loop that says "Places connected to Park:" to show the graph connections clearly.
DSA C#
Hint
Use Console.WriteLine("Places connected to Park:") before the loop.
Practice
(1/5)
1. Why do we need graphs when we already have trees in data structures?
easy
A. Because graphs can model relationships where nodes have multiple connections, unlike trees.
B. Because trees are faster to traverse than graphs.
C. Because graphs use less memory than trees.
D. Because trees cannot store any data.
Solution
Step 1: Understand tree structure limitations
Trees have a strict hierarchy where each node has only one parent, so they cannot represent multiple connections between nodes.
Step 2: Understand graph capabilities
Graphs allow nodes to connect to multiple other nodes without hierarchy, modeling complex relationships like social networks or maps.
Final Answer:
Because graphs can model relationships where nodes have multiple connections, unlike trees. -> Option A
Quick Check:
Graphs model multiple connections [OK]
Hint: Graphs allow many connections per node; trees do not. [OK]
Common Mistakes:
Thinking trees can have multiple parents per node
Confusing memory use between trees and graphs
Assuming trees cannot store data
2. Which of the following is the correct way to declare an adjacency list for a graph in C#?
easy
A. Dictionary graph = new Dictionary();
B. List<int> graph = new List<int>();
C. int[] graph = new int[10];
D. Dictionary graph = new Dictionary();
Solution
Step 1: Identify adjacency list structure
An adjacency list maps each node (int) to a list of connected nodes (List<int>), so Dictionary is suitable.
Step 2: Check other options
List<int> alone cannot map nodes to neighbors; int[] is a fixed array, not a map; Dictionary maps to single int, not list.
Final Answer:
Dictionary graph = new Dictionary(); -> Option D
Quick Check:
Adjacency list = Dictionary with List values [OK]
Hint: Adjacency list uses Dictionary with List values. [OK]
Common Mistakes:
Using List<int> without mapping keys
Using Dictionary instead of List<int>
Using fixed-size arrays for adjacency
3. What will be the output of the following C# code snippet modeling a graph?
var graph = new Dictionary();
graph[1] = new List<int> {2, 3};
graph[2] = new List<int> {1};
graph[3] = new List<int> {1, 4};
graph[4] = new List<int> {3};
foreach(var node in graph)
{
Console.Write(node.Key + ": ");
foreach(var neighbor in node.Value)
Console.Write(neighbor + " ");
Console.WriteLine();
}
medium
A. 1: 2 3
2: 1
3: 4
4: 3
B. 1: 1 2 3 4
2: 1
3: 1 4
4: 3
C. 1: 2 3
2: 1
3: 1 4
4: 3
D. 1: 2 3
2: 3
3: 1 4
4: 3
Solution
Step 1: Understand graph dictionary entries
Node 1 connects to 2 and 3; node 2 connects to 1; node 3 connects to 1 and 4; node 4 connects to 3.
Step 2: Trace the output loop
For each node, print key and neighbors exactly as stored, matching 1: 2 3
2: 1
3: 1 4
4: 3 's output.
Final Answer:
1: 2 3
2: 1
3: 1 4
4: 3 -> Option C
Quick Check:
Print adjacency list as stored [OK]
Hint: Print dictionary keys and their neighbor lists exactly. [OK]
Common Mistakes:
Mixing neighbors between nodes
Printing extra or missing neighbors
Confusing order of neighbors
4. Identify the error in this C# code snippet that tries to add edges to a graph:
var graph = new Dictionary();
graph[1].Add(2);
graph[2] = new List<int> {1};
medium
A. graph[2] should be initialized before adding elements.
B. graph[1] is used before initializing its list, causing a runtime error.
C. Dictionary keys must be strings, not integers.
D. List<int> cannot be used as dictionary values.
Solution
Step 1: Check initialization of graph[1]
graph[1] is accessed to add an element before assigning a List<int>, causing a NullReferenceException.
Step 2: Verify other lines
graph[2] is correctly initialized before use; dictionary keys can be int; List<int> is valid value type.
Final Answer:
graph[1] is used before initializing its list, causing a runtime error. -> Option B
Quick Check:
Accessing uninitialized dictionary entry [OK]
Hint: Initialize list before adding to dictionary key. [OK]
Common Mistakes:
Assuming dictionary keys must be strings
Ignoring null initialization errors
Confusing dictionary value types
5. You want to model a city map where intersections connect to multiple roads, including loops and two-way streets. Which data structure best models this, and why can't a tree be used here?
hard
A. Use a graph because it supports cycles and multiple connections; trees cannot model loops.
B. Use a tree because it is simpler and supports multiple parents per node.
C. Use an array because it stores all intersections linearly.
D. Use a linked list because it models one-way streets well.
Solution
Step 1: Analyze city map requirements
City intersections connect to multiple roads, including loops and two-way streets, needing multiple connections and cycles.
Step 2: Compare tree and graph capabilities
Trees cannot represent cycles or multiple parents; graphs support cycles and multiple edges between nodes.
Final Answer:
Use a graph because it supports cycles and multiple connections; trees cannot model loops. -> Option A
Quick Check:
City map needs cycles = graph [OK]
Hint: Graphs model cycles and multiple connections; trees do not. [OK]
Common Mistakes:
Thinking trees allow cycles
Choosing linear structures for complex maps
Confusing linked lists with graphs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.