Adjacency Matrix用C实现如下:
#include<stdio.h>
#include<stdlib.h>
#include<curses.h>
typedef char VertexType;
typedef int EdgeType;
#define MAXVEX 100
#define INFINITY 11111
//#define DEBUG
typedef struct
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes, numEdges; //定义顶点数,边数
}Graph;
//Locate the vertex you need
int locates(Graph *g,char ch)
{
int i=0;
for(i=0; i<g->numVertexes;i++){
if(g->vexs[i]==ch)
break;
}
if(i>=g->numVertexes) //如果超过顶点数量了,返回-1
return -1;
return i; //return the index of the vertex you are looking
}
//建立一个无方向网图的邻接矩阵表示
void CreateGraph(Graph *g)
{
int i,j,k,w;
printf("Input the number of vertex and arc:\n");
scanf("%d %d", &(g->numVertexes), &(g->numEdges));
printf("#\n");
#ifdef DEBUG
printf("The number is %d and %d.\n",g->numVertexes,g->numEdges);
#endif
printf("The total amount of vertexes is %d. Assign to each.\n",g->numVertexes);
//assign a value to each vertex
for(i=0;i<g->numVertexes;i++){
g->vexs[i]=getchar();
while(g->vexs[i] == '\n'){
g->vexs[i]=getchar();
}
}
#ifdef DEBUG
for(i=0;i<g->numVertexes;i++){
printf("Vexs[i] is %c ",g->vexs[i]);
}
printf("\n");
#endif
//initialize each arc/edge as infinity
for(i=0;i<g->numEdges;i++){
for(j=0;j<g->numEdges;j++){
g->arc[i][j]=INFINITY; //initialize
}
}
for (int i = 0; i < g->numEdges; ++i){
char p,q;
printf("input the i and j of (Vi,Vj), and the weight:\n"); //一条边的两个结点,和这条边的权重
p=getchar();
while(p=='\n'){
p=getchar();
}
q=getchar();
while(q=='\n'){
q=getchar();
}
scanf("%d",&w);
int m=-1;
int n=-1;
m=locates(g,p);
n=locates(g,q);
if(n==-1 || m==-1){
fprintf(stderr,"No such vertex\n");
return;
}
g->arc[m][n]=w;
g->arc[n][m]=g->arc[m][n];
}
}
void printGraph(Graph g){
int i,j;
for(i=0;i<g.numVertexes;i++){
for(j=0;j<g.numVertexes;j++){
printf("%d\t",g.arc[i][j] );
}
printf(