Complete the code to start DFS from the given node.
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int adj : graph[node]) {
if (!visited[[1]]) {
dfs(adj, graph, visited);
}
}
}The DFS visits adjacent nodes. We check if the adjacent node adj is visited before calling DFS recursively.
Complete the code to initialize the visited vector for DFS.
int n = graph.size();
vector<bool> visited([1], false);The visited vector size should match the number of nodes n in the graph.
Fix the error in the DFS recursive call to avoid infinite recursion.
void dfs(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[node] = true;
for (int adj : graph[node]) {
if (!visited[adj]) {
dfs([1], graph, visited);
}
}
}The recursive call must be on the adjacent node adj, not the current node node.
Fill both blanks to create a DFS function that prints nodes in order of visit.
void dfs_print(int node, vector<vector<int>>& graph, vector<bool>& visited) {
visited[[1]] = true;
cout << [2] << " ";
for (int adj : graph[node]) {
if (!visited[adj]) {
dfs_print(adj, graph, visited);
}
}
}We mark the current node node as visited and print it before visiting adjacent nodes.
Fill all three blanks to create a DFS that counts connected components in an undirected graph.
int countComponents(int n, vector<vector<int>>& graph) {
vector<bool> visited(n, false);
int count = 0;
for (int i = 0; i < n; i++) {
if (!visited[[1]]) {
dfs([2], graph, visited);
count[3];
}
}
return count;
}We check if node i is visited, run DFS from i, and increment the count of connected components.
