天天看點

圖的簡單應用--簡單

源程式:

//用一維數組表示頂點,二維數組表示邊,已知圖的頂點和邊,用矩陣表示出頂點和邊的值

//有效邊使用者1表示,無效邊用0表示

#include <stdio.h>

#define MaxVerNum 100

typedef struct

{

char vexs[MaxVerNum]; //頂點數組,相當于私有變量

int edges[MaxVerNum][MaxVerNum]; //頂點之間的邊,也是私有變量

int n;

int e;

}Mgraph;

char vertex[]="12345";

int nvertex=5,nedges=6;

int connection[][2]={{1,2},{2,3},{2,5},{3,5},{3,4},{1,4}};

void CreateMgraph(Mgraph *G)

int i,j,k;

G->n=nvertex;

G->e=nedges;

for(i=0;i<G->n;i++)

G->vexs[i]=vertex[i]; //相當于給私有變量指派

for(j=0;j<G->n;j++)

G->edges[i][j]=0; //初始化邊,邊用矩陣表示,剛開始全部為0000000000000

for(k=0;k<G->e;k++)

{

i=connection[k][0]-1;

j=connection[k][1]-1;

G->edges[i][j]=1;

G->edges[j][i]=1; //此圖為無向圖,若是有向圖,則沒有此行

}

}

void printMgraph(Mgraph &G)

int i,j;

printf("矩陣的頂點數:%d\n",G.n);

printf("矩陣的邊數:%d\n",G.e);

for(i=0;i<G.n;i++)

for(j=0;j<G.n;j++)

printf(" %d",G.edges[i][j]);

printf("\n");

//主函數

void main()

Mgraph g;

CreateMgraph(&g);

printMgraph(g);

運作結果:

圖的簡單應用--簡單