设有一无向网图,其顶点值为字符型并假设各值互不相等,采用邻接矩阵表示法存储表示。设计一个算法,存储该网图并输出其邻接矩阵。
输入格式:
有多组测试数据,每组数据的第一行为两个整数n和e,表示n个顶点和e条边(0<n<20);第二行为其n个顶点的值,按输入顺序进行存储;后面有e行,表示e条边的信息,每条边信息占一行,包括边所依附的顶点下标i和j,以及边上的权值w(可为负),设三者均为整型,数据之间用空格隔开。
输出格式:
输出该网图的邻接矩阵,每组输出占n行,每行有n个数据,每两个数据之间用一个空格隔开,若无边用'#'表示。
输入样例:
在这里给出一组输入。例如:
4 4
ABCD
0 1 4
0 3 3
1 2 6
1 3 8
结尾无空行
输出样例:
在这里给出相应的输出。例如:
0 4 # 3
4 0 6 8
# 6 0 #
3 8 # 0
结尾无空行
同学三连呀🤭
欢迎交流
代码:
#include <iostream>
using namespace std;
#define MaxInt 32767 //表示极大值,即∞
#define MVNum 100 //最大顶点数
#define OK 1
typedef char VerTexType; //假设顶点的数据类型为字符型
typedef int ArcType; //假设边的权值类型为整型
typedef struct{
VerTexType vexs[MVNum]; //顶点表
ArcType arcs[MVNum][MVNum]; //邻接矩阵
int vexnum,arcnum; //图的当前点数和边数
}AMGraph;
int CreateUDN(AMGraph &G,int m,int n){
int i,j,k;
G.vexnum=m;
G.arcnum=n;
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] = MaxInt;
for(k = 0; k < G.arcnum;++k){
VerTexType v1 , v2;
ArcType w;
cin >> i >> j >> w;
G.arcs[i][j] = w;
G.arcs[j][i] = G.arcs[i][j];
}
return OK;
}
int main(){
int m , n;
while(~scanf("%d %d",&m,&n)){
int i,j,k;
AMGraph G;
CreateUDN(G,m,n);
for(i = 0 ; i < G.vexnum ; ++i){
for(j = 0; j < G.vexnum; ++j){
if(j != G.vexnum - 1){
if(i==j){
printf("%d ",0);
}
else{
if(G.arcs[i][j] != MaxInt)
printf("%d ",G.arcs[i][j]);
else
printf("%c ",'#');
}
}
else{
if(i==j){
printf("%d",0);
}
else{
if(G.arcs[i][j] != MaxInt)
printf("%d",G.arcs[i][j]);
else
printf("%c",'#');
}
}
}
printf("\n");
}
}
return 0;
}