#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 30
typedef char VertexType;
//边表 结点
typedef struct ArcNode
{
int adjvex; //临接点对应下标
struct ArcNode *next;
} ArcNode;
//顶点表结点
typedef struct VNode
{
VertexType data;//顶点数据
ArcNode *first;//边表头指针
} VNode,AdjList[MaxVertexNum];
//邻接表
typedef struct Graph
{
AdjList adjList;
int verNum,arcNum;
} GraphAdjList;
void CreateAdjListGraph(GraphAdjList *G)
{
printf("有向图 1 无向图 0: ");
int flag=0;
scanf("%d",&flag);
printf("输入顶点个数 边个数: ");
scanf("%d%d",&G->verNum,&G->arcNum);
for(int i=0; i<G->verNum; i++)
{
printf("请输入第%d个顶点元素: ",i+1);
fflush(stdin);
scanf("%c",&G->adjList[i].data);
G->adjList[i].first=NULL;
}
int u,v;
for(int i=0; i<G->arcNum; i++)
{
printf("请输入u v: ");
scanf("%d%d",&u,&v);
//创建 u-->v
ArcNode *p=(ArcNode*)malloc(sizeof(ArcNode));
p->next=G->adjList[u-1].first;
p->adjvex=v-1;
G->adjList[u-1].first=p;
if(flag==0) //无向图 创建v-->u
{
ArcNode*p2=(ArcNode*)malloc(sizeof(ArcNode));
p2->next=G->adjList[v-1].first;
p2->adjvex=u-1;
G->adjList[v-1].first=p2;
}
}
}
void PrintGraphVertex(GraphAdjList *G)
{
printf("结点: \n");
for(int i=0; i<G->verNum; i++)
{
printf("结点编号%d 结点value%c ",i+1,G->adjList[i].data);
ArcNode*p=G->adjList[i].first;
while(p)
{
printf("%d-->",p->adjvex);
p=p->next;
}
printf("\n");
}
}
//将临接表转换为临接矩阵
void Convert(GraphAdjList *G,int arcs[MaxVertexNum][MaxVertexNum])
{
for(int i=0;i<G->verNum;i++)
{
ArcNode *p=G->adjList[i].first;
while(p)
{
arcs[i+1][p->adjvex]=1;
p=p->next;
}
}
}
int main()
{
GraphAdjList *G;
G=(GraphAdjList*)malloc(sizeof(GraphAdjList));
CreateAdjListGraph(G);
PrintGraphVertex(G);
printf("*******将临接表转换为临接矩阵********\n");
int arcs[MaxVertexNum][MaxVertexNum];
//初始化为0
for(int i=1;i<=G->verNum;i++)
{
for(int j=1;j<=G->verNum;j++)
{
arcs[i][j]=0;
}
}
Convert(G,arcs);
for(int i=1;i<=G->verNum;i++)
{
for(int j=1;j<=G->verNum;j++)
{
printf("%d",arcs[i][j]);
}
printf("\n");
}
}
[图论]--将邻接表转换为临接矩阵
于 2022-07-14 23:26:15 首次发布