图的邻接矩阵创建和输出

#include <iostream>
#include <stdio.h>

using namespace std;

#define MAX_VERTEX_NUM 100

typedef int AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM];

typedef char v_type;

typedef struct {
v_type vexs[MAX_VERTEX_NUM];
AdjMatrix arcs;
int vexnum,arcnum;
}AdjGraph;

bool DirectedorNot() {
char d;

cout << "Is your graph directed or not?(Y/N):" ;
A: cin >> d;

if (d=='Y') return true;
else if (d=='N') return false;
else {
cout << "Please input correctly!" << endl ;
goto A;
}

int LocateVex(AdjGraph G, v_type u) {
int i;
for (i=0; i<G.vexnum; i++) {
if (u==G.vexs[i]) return i;
}

if (i==G.vexnum) {
cout << "Error!" << endl;
exit(1);
}

return 0;
}

void CreatMGraph(AdjGraph &G) {
int i,j,k,w;
v_type v1,v2;
    bool flag;
flag = DirectedorNot();

cout << "Input vexnum & arcnum!" ;
cin >> G.vexnum >> G.arcnum ;
cout << "Input Vertices!" ;
for (i=0; i<G.vexnum; i++) {
cin >> G.vexs[i] ;
}

for (i=0; i<G.vexnum; i++) {
for (j=0; j<G.vexnum; j++) {
G.arcs[i][j] = 0;
}
}

for (k=0; k<G.arcnum; k++) {
cout << "Input Arcs(v1, v2 & w):" ;
cin >> v1 >> v2 >> w ;
i = LocateVex(G, v1);
j = LocateVex(G, v2);
G.arcs[i][j] = w ;
if (!flag)
G.arcs[j][i] = w ;
}

}

void PrintGraph(AdjGraph G) {
int i,j;
printf("Output Vertices:");
printf("%s",G.vexs); printf("/n");
printf("Output AdjMatrix:/n");
for (i=0;i<G.vexnum;i++)
{  for (j=0;j<G.vexnum;j++) 
      printf("%4d",G.arcs[i][j]);
      printf("/n");
}

}

int main() {
    AdjGraph G;

CreatMGraph(G);

PrintGraph(G);

system ("pause");
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值