数据结构与算法编程题45

带权无向图邻接矩阵表示

//参考博客:https://blog.csdn.net/qq_54162207/article/details/117414707
//参考博客:https://blog.csdn.net/Aiden_yan/article/details/121112106
#include <iostream>
using namespace std;

#define Maxsize 100
#define VertexmMaxNum 20
#define ERROR  0
#define OK     1
typedef string VertexType;
typedef int  EdgeType;

typedef struct Graph   //无向图
{
	VertexType vex[VertexmMaxNum];
	EdgeType edge[VertexmMaxNum][VertexmMaxNum];
	int vexnum;     //顶点数
	int edgenum;  //边数
}Graph;

//确定某顶点在G中的位置下标
int locateVex(Graph& G, VertexType v)
{
	for (int i = 0; i < G.vexnum; i++)
	{
		if (v == G.vex[i]) return i;
	}
	return -1;
}

void CreateUG(Graph& G)
{
	int i = 0, j = 0;
	int weight = 0;
	cout << "请输入无向图的顶点数和边数:";
	cin >> G.vexnum >> G.edgenum;
	cout << "请输入顶点:";
	for (i = 0; i < G.vexnum; i++)
	{
		cin >> G.vex[i];
	}
	for (i = 0; i < G.vexnum; i++)
	{
		for (j = 0; j < G.vexnum; j++)
			G.edge[i][j] = 0;
	}
	for (int k = 0; k < G.edgenum; k++)
	{
		cout << "请输入第" << k + 1 << "条边以及边的权值:";
		VertexType v1, v2;

		cin >> v1 >> v2 >> weight;
		int i = locateVex(G, v1);
		int j = locateVex(G, v2);
		G.edge[j][i] = G.edge[i][j] = weight;
	}
}

/*--------打印图的邻接矩阵-----------*/
void PrintfUGraph(Graph G) {
	//将图的邻接矩阵输出在控制台上
	for (int i = 0; i < G.vexnum; i++) {
		cout << G.vex[i] << ":";
		for (int j = 0; j < G.vexnum; j++)
			cout << G.edge[i][j] << " ";
		cout << endl;
	}
}

//顶点信息
//A B C D
//边信息
/*
A B 4
A D 5
B D 7
C D 3
*/
int main(void)
{
	Graph G;
	CreateUG(G);  //不带权无向图
	cout << "  A B C D" << endl;
	PrintfUGraph(G);
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值