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;
}
}
}