Why Shortest Path Is a Graph Problem Not a Tree Problem
📖 Scenario: Imagine you are planning a trip between cities connected by roads. Some cities have multiple roads leading to others, creating loops and multiple routes. You want to find the shortest route from your starting city to your destination.This situation is like a graph, where cities are points (nodes) and roads are connections (edges). Unlike a tree, which has no loops and only one path between points, graphs can have many paths and loops.
🎯 Goal: You will build a simple graph representing cities and roads, then find the shortest path between two cities. This will show why shortest path problems need graphs, not trees.
📋 What You'll Learn
Create a graph using a map where keys are city names and values are slices of connected city names
Add a variable for the starting city
Write a function to find the shortest path using a breadth-first search (BFS) approach
Print the shortest path found from start to destination
💡 Why This Matters
🌍 Real World
Finding shortest routes in maps, network routing, social network connections, and many other applications.
💼 Career
Understanding graph algorithms like shortest path is essential for software engineers working on navigation, logistics, and network systems.
Progress0 / 4 steps
1
Create the graph of cities and roads
Create a variable called graph as a map[string][]string with these exact entries: "A": {"B", "C"}, "B": {"A", "D", "E"}, "C": {"A", "F"}, "D": {"B"}, "E": {"B", "F"}, "F": {"C", "E"}
DSA Go
Hint
Use a map with string keys and slice of strings as values to represent connections.
2
Set the starting city and destination
Add two string variables called start and destination with values "A" and "F" respectively
DSA Go
Hint
Just create two string variables with the exact names and values.
3
Write a function to find the shortest path using BFS
Write a function called shortestPath that takes graph map[string][]string, start string, and destination string and returns a slice of strings representing the shortest path. Use a breadth-first search approach with a queue and a map to track visited nodes and paths.
DSA Go
Hint
Use a queue to store paths and a map to mark visited cities. Expand paths by neighbors until destination is found.
4
Print the shortest path from start to destination
Call the shortestPath function with graph, start, and destination. Store the result in a variable called path. Then print path.
DSA Go
Hint
Call the function and print the returned slice to see the shortest path.
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 do not have nodes
C. Because shortest path algorithms only work on trees
D. Because trees always have weighted 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. Graphs can have cycles and multiple paths between nodes.
Step 2: Relate shortest path to multiple paths
Shortest path problems require checking multiple possible paths to find the minimum distance. This is only possible in graphs with cycles or multiple paths, not in trees where only one path exists.
Final Answer:
Because graphs can have cycles and multiple paths between nodes, unlike trees -> Option A
Quick Check:
Graphs allow multiple paths = shortest path problem [OK]
Hint: Shortest path needs multiple paths, trees have only one [OK]
Common Mistakes:
Thinking trees have cycles
Assuming shortest path only applies to trees
Confusing nodes with edges
2. Which of the following Go code snippets correctly declares a graph using adjacency lists for shortest path calculation?
easy
A. var graph [][]int = make([][]int, 0)
B. var graph []int = make([]int, 10)
C. var graph map[int][]int = make(map[int][]int)
D. var graph map[int]int = make(map[int]int)
Solution
Step 1: Identify correct graph representation
Graphs for shortest path are often represented as adjacency lists: a map from node to list of connected nodes.
Step 2: Check each option
var graph map[int][]int = make(map[int][]int) declares a map from int to slice of ints, perfect for adjacency lists. var graph []int = make([]int, 10) is a slice of ints, not adjacency list. var graph map[int]int = make(map[int]int) maps int to int, not adjacency list. var graph [][]int = make([][]int, 0) is a slice of slices but initialized empty, less common and incomplete.
Final Answer:
var graph map[int][]int = make(map[int][]int) -> Option C
Quick Check:
Adjacency list = map[int][]int [OK]
Hint: Adjacency list uses map[int][]int in Go [OK]
Common Mistakes:
Using map[int]int instead of map[int][]int
Confusing slice of ints with adjacency list
Not initializing the map
3. Consider the following Go code snippet for a graph with edges and weights. What is the output of the shortest path from node 0 to node 3?
package main
import "fmt"
func main() {
graph := map[int]map[int]int{
0: {1: 4, 2: 1},
1: {3: 1},
2: {1: 2, 3: 5},
3: {},
}
dist := map[int]int{0: 0, 1: 999, 2: 999, 3: 999}
visited := map[int]bool{}
for len(visited) < 4 {
u := -1
minDist := 999
for node, d := range dist {
if !visited[node] && d < minDist {
minDist = d
u = node
}
}
if u == -1 {
break
}
visited[u] = true
for v, w := range graph[u] {
if dist[u]+w < dist[v] {
dist[v] = dist[u] + w
}
}
}
fmt.Println(dist[3])
}
4. The following Go code attempts to find the shortest path in a graph but has a bug. What is the bug?
package main
import "fmt"
func main() {
graph := map[int][]int{
0: {1, 2},
1: {3},
2: {1, 3},
3: {},
}
dist := map[int]int{0: 0, 1: 999, 2: 999, 3: 999}
visited := map[int]bool{}
for len(visited) < 4 {
u := -1
minDist := 999
for node, d := range dist {
if !visited[node] && d < minDist {
minDist = d
u = node
}
}
if u == -1 {
break
}
visited[u] = true
for _, v := range graph[u] {
if dist[u]+1 < dist[v] {
dist[v] = dist[u] + 1
}
}
}
fmt.Println(dist[3])
}
medium
A. The graph edges are unweighted but code assumes weight 1, which is correct
B. The code does not handle cycles, causing infinite loop
C. The initial distances are set incorrectly
D. The code uses a map for visited nodes but does not check if all nodes are reachable
Solution
Step 1: Analyze visited and loop condition
The loop runs until all nodes are visited. But if some nodes are unreachable, the loop may break early with u == -1.
Step 2: Check if code handles unreachable nodes
Since unreachable nodes remain with dist=999 and unvisited, the loop breaks early, so dist for unreachable nodes stays 999, which is expected. But the code does not explicitly handle unreachable nodes or report them.
Final Answer:
The code uses a map for visited nodes but does not check if all nodes are reachable -> Option D
Quick Check:
Unreachable nodes not handled = bug [OK]
Hint: Check if unreachable nodes cause early loop break [OK]
Common Mistakes:
Thinking unweighted edges cause error
Assuming infinite loop occurs
Ignoring unreachable nodes
5. You have a graph with nodes representing cities and edges representing roads with distances. Some roads form cycles. Why can't you use a tree-based shortest path algorithm here, and which graph algorithm is suitable instead?
hard
A. Because trees are faster; use Depth-First Search (DFS) instead
B. Because cycles can create multiple paths; use Dijkstra's algorithm for shortest path
C. Because trees have weighted edges; use Breadth-First Search (BFS) for shortest path
D. Because graphs have no cycles; use Prim's algorithm for shortest path
Solution
Step 1: Understand why trees don't fit
Trees have no cycles and only one path between nodes. Graphs with cycles can have multiple paths, so tree algorithms can't handle all cases.
Step 2: Identify suitable algorithm for graphs with cycles
Dijkstra's algorithm works on graphs with weighted edges and cycles to find shortest paths efficiently.
Final Answer:
Because cycles can create multiple paths; use Dijkstra's algorithm for shortest path -> Option B
Quick Check:
Cycles need graph algorithm = Dijkstra [OK]
Hint: Cycles need graph algorithms like Dijkstra, not tree methods [OK]
Common Mistakes:
Using DFS or BFS for weighted shortest path
Confusing Prim's algorithm (for MST) with shortest path
Assuming trees can represent cyclic graphs
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.