![](/img/trans.png)
[英]The connected components in an undirected graph of a given amount of vertices (algorithm)
[英]Given an undirected graph G(V,E), find and print all the connected components of the given graph G
這是我試圖編碼的問題。 我已經編寫了以下代碼,但我不知道如何將元素存儲在 getComponent() 函數中的向量中並在 main 函數中檢索它。
我使用 ans 作為向量變量。 我正在傳遞它的地址,這樣我就不必返回任何東西。 但是在運行代碼時出現編譯錯誤。
#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;
}
}
}
您需要實際創建一個ans
向量並傳遞它的地址:
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;
}
}
之后,您應該用 std::vector 替換所有 C 樣式數組並傳遞引用而不是指針。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.