/** | |
* C: 邻接矩阵表示的”有向网” | |
* | |
* @author zk | |
* @date 2016/11/28 | |
*/ |
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <stdlib.h>
#define MaxInt 32767 //表示极大值
#define MVnun 100 //最大顶点数
#define isLetter(a) ((((a)>=’a’&&((a)<=’z’)))||(((a)>=’A’)&&((a)<=’Z’)))
typedef char VerTexType; //假设顶点的数据类型为字符型
typedef int ArcType; //边的权值类型为整型
typedef struct
{
VerTexType vexs[MVnun]; //顶点表
ArcType arcs[MVnun][MVnun]; //邻接矩阵
int vexnum,arcnum; //图的当前点数和边数
} AMGraph , *PGraph;
/*
* 返回ch在arcs矩阵中的位置,,,,,我觉得应该是在顶点表中的位置
*/
static int get_position(AMGraph g , char ch)
{
int i;
for(i=0; i<g.vexnum; i++)
{
if(g.vexs[i] == ch)
return i;
}
return -1;
}
/*
* 读取一个输入字符
*/
static char read_char()
{
char ch;
do
{
ch = getchar();
}
while(!isLetter(ch));
return ch;
}
/*
* 创建图(自己输入)
*/
AMGraph* creare_graph()
{
char c1,c2;
int vex,edge;
int i,p1,p2;
int weight;
AMGraph* pG;
//输入顶点数和边数
printf(“intput vextex number:\n”);
scanf(“%d”,&vex);
printf(“intput edge number:\n”);
scanf(“%d”,&edge);
if ( vex < 1 || edge < 1 || (edge > (vex * (vex-1))))
{
printf(“input error: invalid parameters!\n”);
return NULL;
}
if ((pG=(AMGraph*)malloc(sizeof(AMGraph))) == NULL )//分配空间
return NULL;
memset(pG, 0, sizeof(AMGraph));
//初始化顶点数和边数
pG->vexnum = vex;
pG->arcnum = edge;
//初始顶点
for(i=0; i< pG->vexnum; i++)
{
printf(“inuput vertex(%d):”,i);
pG->vexs[i] = read_char();
}
//初始化边
for(i = 0; i <pG->arcnum; i++)
{
printf(“intput edge(%d):”,i);
//获取边的两个顶点
c1= read_char();
c2= read_char();
//获取权值
printf(“intput weight”);
scanf(“%d”,&weight);
//获取出c1c2在顶点表中的位置
p1= get_position(*pG,c1);
p2= get_position(*pG,c2);
pG->arcs[p1][p2] = weight;
// pG->arcs[p2][p1] = 1; ///用于无向网
}
return pG;
}
/*
* 打印矩阵队列图
*/
void print_graph(AMGraph pG)
{
int i , j ;
printf(“Adjcency Matrix:\n”);
for(i = 0; i <pG.vexnum; i++)
{
for(j = 0; j <pG.vexnum; j++)
{
printf(“%d “,pG.arcs[i][j]);
}
printf(“\n”);
}
}
int main()
{
AMGraph* pG;
pG = creare_graph(); //创建
print_graph(*pG); //打印
return 0;
}
部分代码参考https://github.com/wangkuiwu/datastructs_and_algorithm/blob/master/source/graph/basic/dg/c/matrix_dg.c
所以非原创,仅做个人练手