使用 C++ 統計無向圖中的邊數


給定任務是統計無向圖中的邊數。無向圖是一組頂點,它們連線在一起形成一個圖,其所有邊都是雙向的。在無向圖中,可以從一個節點到另一個連線的節點任意方向移動。

以下是無向圖的視覺化表示。

現在,根據問題,我們必須找到無向圖中的邊數。

圖中的邊是指連線兩個頂點的線。

輸入 -

insert(graph_list, 0, 1);
insert(graph_list, 0, 2);
insert(graph_list, 1, 2);
insert(graph_list, 1, 4);
insert(graph_list, 2, 4);
insert(graph_list, 2, 3);
insert(graph_list, 3, 4);

輸出 -

count of edges are: 7

我們將採用的解決上述問題的方法 -

  • 初始化一個列表以儲存圖列表的所有頂點,並相應地插入值。

  • 在函式 count_edges 中,宣告一個變數 count=0,它將返回邊的計數。

  • 使用迴圈遍歷列表,直到到達最後一個頂點,並將 count 的值與 graph_list[i].size() 相加,並將其儲存回 count 變數。

  • 到達最後一個頂點後,將 count 的值除以二,並列印結果。

示例

 現場演示

#include<bits/stdc++.h>
using namespace std;
//function to insert vertices
void insert(list<int> graph_list[], int u, int v){
   graph_list[u].push_back(v);
   graph_list[v].push_back(u);
}
//function to count the total number of edges
void count_edges(list<int> graph_list[], int v){
   int count=0;
   //traverse the loop till the vertice is found
   for (int i = 0 ; i < v ; i++){
      count += graph_list[i].size();
   }
   count = count/2;
   cout<<"count of edges are: "<<count;
}
int main(int argc, char* argv[]){
   //creating 5 vertices in a graph
   int vertices = 5;
   //declare list to create a graph and pass the vertices
   list<int> graph_list[vertices];
   //call insert function passing the list variable, vertice, linked vertice
   insert(graph_list, 0, 1);
   insert(graph_list, 0, 2);
   insert(graph_list, 1, 2);
   insert(graph_list, 1, 4);
   insert(graph_list, 2, 4);
   insert(graph_list, 2, 3);
   insert(graph_list, 3, 4);
   //calling count function that will count the edges
   count_edges(graph_list, vertices);
   return 0 ;
}

輸出

如果我們執行上述程式碼,我們將得到以下輸出 -

count of edges are: 7

更新於: 2020年6月6日

960 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.