Why Shortest Path Is a Graph Problem Not a Tree Problem
📖 Scenario: Imagine you are planning a trip in a city with many roads connecting different places. You want to find the shortest way to get from your home to a park. The city roads can have loops and multiple ways to reach the same place.
🎯 Goal: You will create a simple map of places connected by roads using a graph. Then, you will find the shortest path from one place to another. This shows why shortest path problems need graphs, not just trees.
📋 What You'll Learn
Create a graph using a dictionary where keys are place names and values are lists of connected places with distances
Add a starting place variable
Write a function to find the shortest path using a simple algorithm
Print the shortest path and its total distance
💡 Why This Matters
🌍 Real World
Finding shortest routes in maps, GPS navigation, and network routing uses graph shortest path algorithms.
💼 Career
Understanding graph problems and shortest path algorithms is key for software engineers working on mapping, logistics, and network systems.
Progress0 / 4 steps
1
Create the graph data structure
Create a variable called city_map as a dictionary with these exact entries: "Home": [("Cafe", 5), ("Library", 10)], "Cafe": [("Park", 3)], "Library": [("Park", 1)], "Park": []
DSA Rust
Hint
Use std::collections::HashMap::from to create the dictionary with keys as place names and values as vectors of tuples with connected place and distance.
2
Set the starting place
Create a variable called start and set it to the string "Home"
DSA Rust
Hint
Just create a string variable start and assign it the value "Home".
3
Write a function to find the shortest path
Write a function called shortest_path that takes city_map and start as parameters and returns a dictionary with the shortest distances from start to all other places using a simple breadth-first search approach
DSA Rust
Hint
Use a queue to explore places starting from start. Keep track of shortest distances in a dictionary. Update distances when you find a shorter path.
4
Print the shortest path distances
Call the shortest_path function with &city_map and start, store the result in distances, then print distances
DSA Rust
Hint
Call shortest_path(&city_map, start) and print the returned dictionary.
Practice
(1/5)
1. Why is finding the shortest path usually considered a graph problem rather than a tree problem?
easy
A. Because graphs can have cycles and multiple paths between nodes, unlike trees.
B. Because trees always have weighted edges, making shortest path trivial.
C. Because trees do not have nodes connected by edges.
D. Because shortest path algorithms only work on graphs with no edges.
Solution
Step 1: Understand the structure of trees and graphs
Trees are a special type of graph with no cycles and exactly one path between any two nodes.
Step 2: Analyze shortest path requirements
Shortest path problems need to consider multiple paths and cycles, which only general graphs can have.
Final Answer:
Because graphs can have cycles and multiple paths between nodes, unlike trees. -> Option A
Quick Check:
Graph complexity = shortest path problem [OK]
Hint: Shortest path needs multiple paths; trees have only one [OK]
Common Mistakes:
Thinking trees have cycles
Assuming shortest path is trivial in trees
Confusing edges with nodes
2. Which Rust code snippet correctly declares a graph using adjacency lists for shortest path problems?
easy
A. let graph: Vec> = vec![vec![]; n];
B. let graph: Vec<(usize, usize)> = vec![(0, 0); n];
C. let graph: Vec<usize> = vec![0; n];
D. let graph: HashMap = HashMap::new();
Solution
Step 1: Identify adjacency list structure
An adjacency list for a weighted graph stores a vector of neighbors with weights, e.g., Vec>.
Step 2: Match Rust syntax
let graph: Vec> = vec![vec![]; n]; correctly initializes a vector of vectors of tuples (neighbor, weight) with size n.
Final Answer:
let graph: Vec> = vec![vec![]; n]; -> Option A
Quick Check:
Adjacency list = Vec of Vec of (node, weight) [OK]
Hint: Adjacency list = Vec> in Rust [OK]
Common Mistakes:
Using flat Vec instead of nested Vec
Confusing HashMap with adjacency list
Wrong tuple types for edges
3. Consider this Rust code snippet for a graph with edges: (0->1:2), (0->2:5), (1->2:1). What is the shortest path distance from node 0 to 2 using Dijkstra's algorithm?
medium
A. 5
B. 2
C. 6
D. 3
Solution
Step 1: List all paths from 0 to 2
Paths: 0->2 with cost 5, 0->1->2 with cost 2+1=3.
Step 2: Choose the minimum cost path
Shortest path cost is 3 via 0->1->2.
Final Answer:
3 -> Option D
Quick Check:
Minimum path cost = 3 [OK]
Hint: Check all paths, pick smallest sum [OK]
Common Mistakes:
Choosing direct edge without checking alternate paths
Adding weights incorrectly
Ignoring intermediate nodes
4. This Rust code tries to find shortest path but fails. What is the main bug?
let mut dist = vec![usize::MAX; n];
dist[0] = 0;
for i in 0..n {
for &(v, w) in &graph[i] {
if dist[i] + w < dist[v] {
dist[v] = dist[i] + w;
}
}
}
medium
A. It uses usize::MAX which causes panic on addition.
B. It does not handle cycles properly, needs multiple iterations.
C. It initializes dist with zeros instead of max values.
D. It updates dist[v] without checking if v is visited.
Solution
Step 1: Analyze the loop structure
The code runs only one pass over all edges, which is insufficient for graphs with cycles or longer paths.