(图6-1)Vertex Degrees--C语言

Write a program to obtain the in-degrees and out-degrees of all the vertices in a given graph Graph.

函数接口定义:

void GetDegrees( LGraph Graph, int in[], int out[] );

where LGraph is defined as the following:

typedef struct AdjVNode *PtrToAdjVNode;
struct AdjVNode{
Vertex AdjV;
PtrToAdjVNode Next;
};
typedef struct Vnode{
PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{
int Nv;
int Ne;
AdjList G;
};
typedef PtrToGNode LGraph;

The function GetDegrees must save the in-degrees and out-degrees of all the vertices in in and out, respectively.
Note: Although the vertices are numbered from 1 to MaxVertexNum, they are indexed from 0 in the LGraph structure.

裁判测试程序样例:

#include <stdio.h>
#include <stdlib.h>
typedef enum {false, true} bool;
#define MaxVertexNum 10  /* maximum number of vertices */
typedef int Vertex;      /* vertices are numbered from 1 to MaxVertexNum */
typedef struct AdjVNode *PtrToAdjVNode; 
struct AdjVNode{
    Vertex AdjV;
    PtrToAdjVNode Next;
};
typedef struct Vnode{
    PtrToAdjVNode FirstEdge;
} AdjList[MaxVertexNum];
typedef struct GNode *PtrToGNode;
struct GNode{  
    int Nv;
    int Ne;
    AdjList G;
};
typedef PtrToGNode LGraph;
LGraph ReadG(); /* details omitted */
void GetDegrees( LGraph Graph, int in[], int out[] );
int main()
{
    int i;
    int in[MaxVertexNum], out[MaxVertexNum];
    LGraph G = ReadG();
    GetDegrees(G, in, out);
    printf("in-degrees:");
    for (i=0; i<G->Nv; i++) {
        printf(" %d", in[i]);
    }
    printf("\n");
    printf("out-degrees:");
    for (i=0; i<G->Nv; i++) {
        printf(" %d", out[i]);
    }
    printf("\n");
    return 0;
}
/* Your function will be put here */

输入样例:

在这里插入图片描述

6 8
1 2
1 3
5 2
5 4
2 3
2 6
3 4
6 4

输出样例:

in-degrees: 0 2 2 3 0 1
out-degrees: 2 2 1 0 2 1

知识点:

在这里插入图片描述

代码:

//计算出度in,入度out
void GetDegrees( LGraph Graph, int in[], int out[] )
{
    //初始化出度,入度数组
    for(int j=0;j<Graph->Nv;j++)
    {
        in[j]=0;
        out[j]=0;
    }
    //Graph->Nv为顶点个数,图为邻接表的形式
    for(int i=0;i<Graph->Nv;i++)
    {
        PtrToAdjVNode p=Graph->G[i].FirstEdge;
        while(p)
        {
            out[i]++;//结点个数即为出度
            in[p->AdjV]++;//指向的结点就是出度指向的顶点,则给指向的顶点记数
            p=p->Next;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值