邻接矩阵和邻接表实现图
1.邻接矩阵实现
#include<stdio.h>
#include<stdlib.h>
#define MaxVertexNum 100
typedef int weightType;
typedef int Vertex;
typedef int DataType;
typedef struct GNode *ptrToGNode;
struct GNode{ // 图
int Nv; // 顶点数
int Ne; // 边数
weightType G[MaxVertexNum][MaxVertexNum];
DataType Data[MaxVertexNum]; // 存顶点的数据
};
typedef ptrToGNode MGraph;
typedef struct ENode *ptrToENode;
struct ENode{ // 边
Vertex V1,V2; // 有向边<V1,V2>
weightType Weight; // 权重
};
typedef ptrToENode Edge;
MGraph CreateGragh(int VertexNum)
{
Vertex V,W;
MGraph Graph;
Graph = (MGraph)malloc(sizeof(struct GNode));
Graph->Nv = VertexNum;
Graph->Ne = 0;
for(V=0;V<Graph->Nv;V++){
for(W=0;W<Graph->Nv;W++){
Graph->G[V][W] = 0;
}
}
return Graph;
}
MGraph Insert(MGraph Graph,Edge E)
{
Graph->G[E->V1][E->V2] = E->Weight;
Graph->G[E->V2][E->V1] = E->Weight;
}
MGraph BuildGraph()
{
MGraph Graph;
Edge E;
Vertex V;
int Nv,i;
printf("Enter Node nums:");
scanf("%d",&Nv);
Graph = CreateGragh(Nv);
printf("Enter Edge nums:");
scanf("%d",&(Graph->Ne));
if(Graph->Ne != 0){
E = (Edge)malloc(sizeof(struct ENode));
for(i=0 ; i<Graph->Ne ; i++){
printf("Enter Edge:");
scanf("%d %d %d",&E->V1,&E->V2,&E->Weight);
Insert(Graph,E);
}
}
return Graph;
}
void print(MGraph Graph)
{
Vertex V,W;
for(V=0;V<Graph->Nv;V++){
for(W=0;W<Graph->Nv;W++){
printf("%d ",Graph->G[V][W]);
}
printf("\n");
}
}
int main()
{
MGraph Graph;
Graph = BuildGraph();
print(Graph);
return 0;
}
效果图:
2.邻接表实现
#include <stdio.h>
#include <stdlib.h>
#define MAX_VERTEX_NUM 100
typedef struct AdjVNode *AdjList;
struct AdjVNode{
int weight;
int adjv;
AdjList next;
};
AdjList Graph[MAX_VERTEX_NUM];
int Ne,Nv;
void BuildGraph()
{
int i;
int v1,v2,w;
AdjList NewNode;
printf("Enter Node nums:");
scanf("%d",&Nv);
for(i=0;i<Nv;i++){
Graph[i] = (AdjList)malloc(sizeof(struct AdjVNode));
Graph[i]->adjv = i;
Graph[i]->next = NULL;
}
printf("Enter Edge nums:");
scanf("%d",&Ne);
for(i=0;i<Ne;i++){
printf("Enter edge:");
scanf("%d %d %d",&v1,&v2,&w);
NewNode = (AdjList)malloc(sizeof(struct AdjVNode));
NewNode->adjv = v1;
NewNode->weight = w;
NewNode->next = Graph[v2]->next;
Graph[v2]->next = NewNode;
NewNode = (AdjList)malloc(sizeof(struct AdjVNode));
NewNode->adjv = v2;
NewNode->weight = w;
NewNode->next = Graph[v1]->next;
Graph[v1]->next = NewNode;
}
}
void print()
{
AdjList temp;
int i;
for(i=0;i<Nv;i++){
temp = Graph[i];
while(temp != 0){
printf("%d ",temp->adjv);
temp = temp->next;
}
printf("\n");
}
}
int main()
{
BuildGraph();
print();
return 0;
}
效果图