3.1 建立无向图的邻接矩阵存储

#include "pch.h"
#include <iostream>
#include <iomanip>		//格式化输出头文件

typedef char VertexType;	//顶点类型
typedef int EdgeType;		//边上的权值类型
#define MAXVEX 100			//最大顶点数
#define myINFINITY 65535	//用65535代表正无穷

typedef struct {
public:
	VertexType vexs[MAXVEX];		//顶点表
	EdgeType arcs[MAXVEX][MAXVEX];	//邻接矩阵,作为边表
	int numVertexes, numEdges;		//图中当前的顶点数和边数
}MGraph;

/*建立无向网的邻接矩阵表示*/
void CreateMGraph(MGraph* G) {
	std::cout << "请依次输入顶点数和边数:";
	std::cin >> G->numVertexes >> G->numEdges;

	for (int i = 0; i < G->numVertexes; ++i) {		//读入顶点信息,建立顶点表
		std::cout << "请输入第 " << i + 1 << " 个顶点的信息:";
		std::cin >> G->vexs[i];
	}
	for (int i = 0; i < G->numVertexes; ++i) {		//邻接矩阵初始化
		for (int j = 0; j < G->numVertexes; ++j)
			G->arcs[i][j] = myINFINITY;
		G->arcs[i][i] = 0;
	}

	for (int k = 0; k < G->numEdges; ++k) {		//读入numEdeges条边,建立邻接矩阵
		int i = 0, j = 0;
		EdgeType w;
		std::cout << "请依次输入边(Vi, Vj)的上标i,下标j和权 W:";
		std::cin >> i >> j >> w;
		G->arcs[i][j] = w;
		G->arcs[j][i] = w;		//无向图的矩阵对称,有向图则去除这一行
	}
}

/*打印无向网*/
void ShowMGraph(const MGraph& G) {
	std::cout << std::endl << "邻接矩阵如下:" << std::endl;
	std::cout << "    V0";
	for (int i = 1; i < G.numVertexes; ++i)
		std::cout << "  V" << i;
	for (int i = 0; i < G.numVertexes; ++i) {
		std::cout << "\nV" << i;
		for (int j = 0; j < G.numVertexes; ++j) {
			if (G.arcs[i][j] != myINFINITY)
				std::cout << std::right << std::setw(4) << G.arcs[i][j];
			else
				std::cout << std::right << std::setw(4) << "∞";
		}

	}
	std::cout << std::endl;
}

int main() {
	MGraph G;
	CreateMGraph(&G);
	ShowMGraph(G);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40843865/article/details/89221845
今日推荐