想要无向图,将weight(权值)输出为1即可, 代码还可以还可以再改进,而且非常需要改进
图片
图片来自百度
v0 v1 v2 v3 v4 为顶点的值
. h 文件
#include<stdio.h>
#include<stdlib.h>
#define maxver 100
/*
# is infinity
*/
// ================= 0 ======================
typedef struct{
int vertexnum; //顶点数
int arcnum; //
int ver[maxver];
int arc[maxver][maxver];
}lgraph;
typedef struct{
int begin;
int end;
int weight;
}lEdge;
// ================= 1 ===================
void creatGraph(lgraph *G , lEdge *E)
{
int i,j;
printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("please input the number of vertexnum and arcnum : ");
scanf("%d%d",&(G->vertexnum),&(G->arcnum));
for(i=0;i<G->vertexnum;i++){
for(j=0;j<G->vertexnum;j++){
if(i==j){
G->arc[i][j]=0;
}else{
G->arc[i][j]=9999;
}
}
}
printf("please input the value of vertex \n");
for(i=0;i<G->vertexnum;i++){
printf("The vertex of the %d :",i+1);
scanf("%d",&(G->ver[i]));
}
printf("\n---------------------------------\n");
printf("please input the value of arc \n");
for(i=0;i<G->arcnum;i++){
printf("The arc of the %d :",i+1);
scanf("%d%d%d",&(E->begin),&(E->end),&(E->weight));
G->arc[E->begin-1][E->end-1]=E->weight;
G->arc[E->end-1][E->begin-1]=E->weight;
}
printf("\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
}
//=================== 2 ====================
void showgraph(lgraph *G)
{
int i,j;
printf("\n===================================\n");
for(i=0;i<G->vertexnum;i++){
printf("\t");
for(j=0;j<G->vertexnum;j++){
if(G->arc[i][j]==9999){
printf("# ");
}else{
printf("%d ",G->arc[i][j]);
}
}
printf("\n");
}
printf("===================================\n");
}
.c 文件
#include<stdio.h>
#include "linjiejuzhen.h"
int main()
{
lgraph graph;
lEdge edge;
creatGraph(&graph,&edge);
showgraph(&graph);
return 0;
}
总的来说就是将数据元素在一维数组的下标,在二维数组中体现,并给予二维数组值,即对应边的权值