6-2 统计无向图中各顶点的度
本题要求实现一个函数,统计无向图中各顶点的度。
函数接口定义:
void degree(MGraph Graph,int *num);
其中,Graph为采用 邻接矩阵
作为存储结构的无向图,函数degree计算无向图中各顶点的度,并将相应结果存储在数组num中。
裁判测试程序样例:
#include <stdio.h> #include <stdlib.h> #define INFINITY 65535 //∞设为65535 #define MAXVERTEXNUM 100 //最大顶点数设为100 typedef struct GNode *PtrToGNode; struct GNode{ int Nv; //顶点数 int Ne; //边数 int G[MAXVERTEXNUM][MAXVERTEXNUM]; //邻接矩阵 char Data[MAXVERTEXNUM]; }; typedef PtrToGNode MGraph; //以邻接矩阵存储的图类型 void degree(MGraph Graph,int *num); MGraph BuildGraph() { MGraph Graph; int i,j,k,weight; char a,b; Graph = (PtrToGNode)malloc(sizeof(struct GNode)); scanf("%d %d",&Graph->Nv,&Graph->Ne); for(i = 0;i < Graph->Nv; i++) { getchar(); scanf("%c",&Graph->Data[i]); //输入顶点数据 } for(i = 0;i < Graph->Nv; i++) for(j = 0;j < Graph->Nv; j++) Graph->G[i][j] = INFINITY; //初始化邻接矩阵 /*此处输入边的信息*/ for(k = 0;k < Graph->Ne ; k++) { getchar(); scanf("%c %c %d",&a,&b,&weight); for( i = 0; Graph->Data[i] != a;i++) ; //找到顶点a在邻接矩阵中的下标 for( j = 0; Graph->Data[j] != b;j++) ; //找到顶点b在邻接矩阵中的下标 Graph->G[i][j] = weight; Graph->G[j][i] = weight; } return Graph; } int main() { MGraph Graph1; int num[100]={0}; //num统计各顶点的度 int i; /* 建立图的邻接矩阵 */ Graph1 = BuildGraph(); degree(Graph1,&num[0]); for(i = 0;i < Graph1->Nv; i++) { printf("顶点%c的度为:%d",Graph1->Data[i],num[i]); printf("\n"); } return 0; }
输入样例:
5 8
A B C D E
A B 8
A E 4
B C 7
B D 12
B E 5
C D 6
C E 11
D E 3
标签:num,int,Graph,邻接矩阵,---,++,无向,顶点 From: https://blog.csdn.net/2401_84341430/article/details/144774921void degree(MGraph Graph,int *num)
{
int i;
for(int i=0;i<Graph->Nv;i++)
{
for(int j=0;j<Graph->Nv;j++)
{
if(Graph->G[i][j]!=INFINITY)
num[i]++;
}
}
}