Embercode
✕
GraphsQuick quiz

Graph bug hunt

8 questions. Covers Debugging lab: graph bugs.

Questions 1 to 5 of 8

  1. 1. A teammate wrote this function to store a directed graph, where an edge a to b means you can go from a to b only: ``cpp Graph build(int n, const std::vector<std::pair<int, int>>& edges) { Graph g(n); for (auto [a, b] : edges) { g[a].push_back(b); g[b].push_back(a); } return g; } `` What is the bug?
  2. 2. What does this program print? ``cpp Graph g = build(4, {{0, 1}, {0, 2}, {1, 3}, {2, 3}}); for (int x : reachableFrom(g, 0)) std::cout << x << ' '; ` Here build stores only the given directed edges, and reachableFrom is the explicit-stack search from Lab 3 that marks a node when it is pushed. `cpp std::vector<int> reachableFrom(const Graph& g, int start) { std::vector<bool> seen(g.size(), false); std::stack<int> todo; todo.push(start); seen[start] = true; std::vector<int> order; while (!todo.empty()) { int u = todo.top(); todo.pop(); order.push_back(u); for (int v : g[u]) { if (!seen[v]) { seen[v] = true; todo.push(v); } } } return order; } ``
  3. 3. In the Lab 4 test table, which is the smallest number of nodes where the recursive DFS on a path crashed with exit code 139?
  4. 4. This recursive search is meant to count the nodes reachable from node 0. It crashes on the graph below. ``cpp void dfs(const Graph& g, int u, int& count) { ++count; for (int v : g[u]) { dfs(g, v, count); } } int main() { Graph g = {{1}, {0}}; // 0 -> 1 -> 0 int count = 0; dfs(g, 0, count); std::cout << "reachable: " << count << '\n'; } `` What happens when it runs?
  5. 5. This BFS is meant to visit every node once, but node 3 is popped twice on a real run. Here the mark is set when a node is popped. ``cpp Graph g = {{1, 2}, {3}, {3}, {}}; std::vector<bool> seen(g.size(), false); std::queue<int> q; q.push(0); seen[0] = true; while (!q.empty()) { int u = q.front(); q.pop(); seen[u] = true; for (int v : g[u]) { if (!seen[v]) q.push(v); } } `` Why is node 3 popped twice?

5 question(s) left on this page.