Which reason best explains why shortest path algorithms are designed for graphs and not just trees?
Think about the structure of trees versus graphs and how cycles affect pathfinding.
Trees have no cycles and exactly one path between any two nodes, so shortest path is straightforward. Graphs can have cycles and multiple paths, requiring algorithms like Dijkstra's.
Consider the following C++ code snippet that tries to find shortest paths using BFS on two structures: a tree and a graph. What is the printed output for the graph?
/* Graph adjacency list with cycle */ #include <iostream> #include <vector> #include <queue> using namespace std; int main() { vector<vector<int>> graph = {{1,2}, {0,2}, {0,1,3}, {2}}; vector<int> dist(4, -1); queue<int> q; dist[0] = 0; q.push(0); while(!q.empty()) { int u = q.front(); q.pop(); for(int v : graph[u]) { if(dist[v] == -1) { dist[v] = dist[u] + 1; q.push(v); } } } for(int i=0; i<4; i++) cout << dist[i] << " "; return 0; }
Trace BFS levels starting from node 0.
BFS finds shortest distance in unweighted graphs. Node 0 distance is 0, nodes 1 and 2 are neighbors (distance 1), node 3 is neighbor of 2 (distance 2).
Given this code snippet for shortest path, what error or problem will occur when run on a graph with cycles?
/* Incorrect shortest path using DFS */ #include <iostream> #include <vector> using namespace std; vector<int> dist; void dfs(int u, int d, vector<vector<int>>& graph) { dist[u] = d; for(int v : graph[u]) { if(dist[v] == -1) { dfs(v, d+1, graph); } } } int main() { vector<vector<int>> graph = {{1,2}, {0,2}, {0,1,3}, {2}}; dist.assign(4, -1); dfs(0, 0, graph); for(int i=0; i<4; i++) cout << dist[i] << " "; return 0; }
Think about how DFS handles revisiting nodes in cycles.
DFS without proper cycle checks can revisit nodes endlessly in graphs with cycles, causing infinite recursion or stack overflow.
Which data structure is best suited to implement Dijkstra's algorithm efficiently on a weighted graph?
Think about how Dijkstra picks the next node with smallest distance.
Dijkstra's algorithm uses a priority queue to always pick the node with the smallest tentative distance next, ensuring correctness and efficiency.
Which statement best explains why shortest path problems are generally studied in graphs rather than trees?
Consider the structural differences and path options in trees vs graphs.
Graphs can have cycles and multiple paths between nodes, so shortest path algorithms must handle these complexities. Trees have exactly one path between nodes, so shortest path is trivial.
