环境:VS2017
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXVEX 100 //最大顶点数,用户自定义
#define INFINITY 65535
typedef int Status;
typedef char VertexType;
typedef int EdgeType;
typedef struct
{
VertexType vexs[MAXVEX]; //顶点表
EdgeType arc[MAXVEX][MAXVEX]; //边表
int numNodes, numEdges; //图中当前的顶点和边表
}MGraph;
//建立无向网图的邻接矩阵
void CreateMGraph(MGraph *G)
{
int i, j, k, w;
printf("输入顶点数和边数:\n");
scanf_s("%d%d", &G->numNodes, &G->numEdges); //输入顶点数和边数
for (i = 0; i < G->numNodes; i++)
scanf_s(&G->vexs[i]);
for (i = 0; i < G->numNodes; i++) //初始化
for (j = 0; j < G->numNodes; j++)
G->arc[i][j] = INFINITY;
for (k = 0; k < G->numEdges; k++)
{
printf("输入边(vi,vj)上的下标i,下标j和权w:\n");
scanf_s("%d%d%d", &i, &j, &w);
G->arc[i][j] = w;
G->arc[j][i] = G->arc[i][j]; //无向图,矩阵对称
}
for (i = 0; i < G->numNodes; i++)
{
for (j = 0; j < G->numNodes; j++)
{
printf("%d\t",G->arc[i][j]);
}
printf("\n");
}
}
int main()
{
MGraph G;
CreateMGraph(&G);
system("pause");
return 0;
}
测试如下:
输入顶点数和边数:
3 3
输入边(vi,vj)上的下标i,下标j和权w:
0 0 1
输入边(vi,vj)上的下标i,下标j和权w:
1 1 3
输入边(vi,vj)上的下标i,下标j和权w:
1 2 5
1 65535 65535
65535 3 5
65535 5 65535