使用 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.