简体   繁体   中英

Given an undirected graph G(V,E), find and print all the connected components of the given graph G

This is the question I am trying to code. I have written the following code but I don't know how can I store the elements in the vector in getComponent() function and retrieve it inside main function.

I have used ans as a vector variable. I am passing its address so that I do not have to return anything. But I am getting compilation error while running the code.

#include<vector>
#include <bits/stdc++.h>
using namespace std;

void getComponent(int **edges, int n, int sv, int * visited, vector<int>*ans){
    visited[sv] = 1;
    
    ans->push_back(sv);
    for(int i = 0; i < n; i++){
        if(i == sv)continue;
        
        if(edges[sv][i] == 1){
            if(visited[i] == 0)
                getComponent(edges, n, i, visited, ans);
        }
    }
}

int main() {
    // Write your code here
    
    int n, e;
    cin>>n>>e;
    
    int **edges = new int *[n];
    
    for(int i = 0; i < n; i++){
        edges[i] = new int[n];
        for(int j = 0; j < n; j++){
            edges[i][j] = 0;
        }
    }
    
    for(int i = 0; i <e; i++){
        int a, b;
        cin>>a>>b;
        
        edges[a][b] = 1;
        edges[b][a] = 1;
    }
    
    int *visited = new int[n];
    
    for(int i = 0; i < n; i++)
        visited[i] = 0;
    
    
    
    for(int i = 0; i < n; i++){
        if(visited[i] == 0){
            vector<int>*ans;
            getComponent(edges, n, i, visited, ans);

            for (auto x : ans)
                cout << x << " ";
            cout<<endl;
        }
            
    }
}

You need to actually create an ans vector and pass it's address:

for(int i = 0; i < n; i++){
    if(visited[i] == 0){
        vector<int> ans;
        getComponent(edges, n, i, visited, &ans);

        for (auto x : ans)
            cout << x << " ";
        cout<<endl;
    }
        
}

After that you should replace all C-style arrays with std::vector and pass references instead of pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM