8 questions. Covers Debugging lab: graph bugs.
Questions 1 to 5 of 8
a
b
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; }
push_back
cpp Graph g = build(4, {{0, 1}, {0, 2}, {1, 3}, {2, 3}}); for (int x : reachableFrom(g, 0)) std::cout << x << ' ';
Here
stores only the given directed edges, and
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; }
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'; }
reachable: 2
reachable: 1
count
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); } }
std::stack
seen[0]
5 question(s) left on this page.