Consider why shortest path problems are generally solved on graphs rather than trees. Which reason best explains this?
Think about the structure of a tree and how many paths exist between two nodes.
Trees are acyclic connected graphs, so there is exactly one path between any two nodes. This makes shortest path trivial and unique. Graphs can have cycles and multiple paths, so shortest path algorithms are needed there.
Given the following adjacency list representations, what is the shortest path length from node 0 to node 3?
Tree adjacency: 0->1, 1->2, 2->3
Graph adjacency: 0->1, 1->2, 2->3, 0->3
int tree_adj[4][1] = {{1}, {2}, {3}, {-1}}; int graph_adj[4][2] = {{1,3}, {2,-1}, {3,-1}, {-1,-1}}; // Shortest path length from 0 to 3 in tree and graph
Check the direct edges from 0 to 3 in both structures.
In the tree, the only path from 0 to 3 is through nodes 1 and 2, so length is 3 edges. In the graph, there is a direct edge from 0 to 3, so shortest path length is 1.
Consider this pseudo-code for shortest path on a graph:
function shortestPath(graph, start, end):
visited = set()
queue = [start]
while queue not empty:
node = queue.pop()
if node == end:
return distance[node]
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
distance[neighbor] = distance[node] + 1
queue.append(neighbor)Why might this fail or give wrong results on graphs with cycles?
Think about when nodes are marked visited and how that affects path discovery.
Marking nodes visited when first discovered can prevent finding shorter paths later if cycles exist. Proper shortest path algorithms revisit nodes if a shorter path is found.
Find the syntax error in this C code snippet for BFS shortest path:
void bfs(int graph[][MAX], int start, int n) {
int queue[MAX], front = 0, rear = 0;
int visited[MAX] = {0};
queue[rear++] = start;
visited[start] = 1
while (front != rear) {
int node = queue[front++];
for (int i = 0; i < n; i++) {
if (graph[node][i] && !visited[i]) {
queue[rear++] = i;
visited[i] = 1;
}
}
}
}Look carefully at each line for missing punctuation.
The line 'visited[start] = 1' is missing a semicolon at the end, causing a syntax error.
Which statement best explains why Dijkstra's algorithm is essential for shortest path in graphs but unnecessary in trees?
Consider the uniqueness of paths in trees and the role of edge weights.
Trees have exactly one path between any two nodes, so shortest path is that path regardless of weights. Graphs can have multiple paths and cycles, so Dijkstra's algorithm finds the minimum weighted path.