The main issue was the fact that you forgot to set the sizes of the vectors. That was causing the segmentation fault.
But there are several other issues with your code:
The logic to detect connectivity is not correct. In practice, with your code, the connection of the last node only determines the connectivity of the graph. And this last node is always connected, as you start from this node for the DFS.
Here for (int i = 0; i < 3; i++)
you use a 0-indexing. You forgot that in the rest of the code, you are using 1-indexing. The best will be to use 0-indexing everywhere. Nevertheless, in the follwing code, I keep the 1-indexing, to show how to cope with it, in particular concerning the size of the arrays.
You should avoid the use of magic constant like 3
in the code.
#include <iostream>
#include <vector>
//using namespace std;
std::vector<std::vector<int>> adj;
std::vector<bool> visited;
void dfs(int v){
visited[v] = true;
for (int u : adj[v]) {
if (!visited[u])
dfs(u);
}
}
int main(){
int n_nodes = 3;
visited.resize(n_nodes+1); // <-- !!!
adj.resize(n_nodes+1); // <-- !!!
adj[1].push_back(2);
adj[2].push_back(3);
adj[3].push_back(1);
dfs(3);
bool connected = true;
for(int i = 1; i <= n_nodes; i++) { // 1-indexed
if(!visited[i]){
connected = false;
}
}
if(connected) {
std::cout << "connected" << std::endl;
} else {
std::cout << "it isn't connected" << std::endl;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…