邻接矩阵-数据结构

邻接矩阵

#define _CRT_SECURE_NO_WARNINGS
#include "iostream"
#include "stdlib.h"
#include "windows.h"
#define OK  1
#define MVNum 100
#define MaxInt 32767
using namespace std;

typedef char VerType;
typedef int ArcType;

typedef struct {
	VerType vexs[MVNum];
	ArcType arcs[MVNum][MVNum];
	int vexnum, arcnum;
}AMGraph;

int visited[MaxInt] = { 0 };

void InitGraph(AMGraph &G);
int LocateVex(AMGraph G, VerType V);//查找值为u的顶点
void InsertVex(AMGraph &G, VerType V);//图中插入一个值为v的顶点
void InsertArc(AMGraph &G, VerType V, VerType U, ArcType W);//图中插入一条边
void DeleteArc(AMGraph &G, VerType V, VerType U);//删除一条边
void DeleteVex(AMGraph &G, VerType V);//删除一个项点
void CreateUDN(AMGraph &G);//建立一个无向网
void DFS_AM(AMGraph G, VerType V);//深度遍历连通图
void BFS_AM(AMGraph G, VerType V);//广度遍历连通图

int main() {
	AMGraph G;
	InitGraph(G);
	CreateUDN(G);
	DFS_AM(G, 'a');
	system("pause");
	return 0;
}

void InitGraph(AMGraph & G)
{
	int i, j;
	G.vexnum = G.arcnum = 0;
	for (i = 0; i < MVNum; i++)
		for (j = 0; j < MVNum; j++)
			G.arcs[i][j] = MaxInt;
}

int LocateVex(AMGraph G, VerType V)
{
	for (int i = 0; i < G.vexnum; i++)
		if (G.vexs[i] == V)
			return i;
	return -1;
}

void InsertVex(AMGraph & G, VerType V)
{
	G.vexs[G.vexnum] = V;
	G.vexnum++;
}

void InsertArc(AMGraph & G, VerType V, VerType U, ArcType W)
{
	int i = LocateVex(G, V);
	int j = LocateVex(G, U);
	if (i == -1 || j == -1)
		return;
	G.arcs[i][j] = G.arcs[j][i] = W;
	G.arcnum++;
}

void DeleteArc(AMGraph & G, VerType V, VerType U)
{
	int i = LocateVex(G, V);
	int j = LocateVex(G, V);
	if (i == -1 || j == -1)
		return;
	G.arcs[i][j] = G.arcs[j][i] = MaxInt;
	G.arcnum--;
}

void DeleteVex(AMGraph & G, VerType V)
{
	int i, j, w, s = 0;
	i = LocateVex(G, V);
	if (i == ERROR)
		return;
	//删除与顶点v相关联的边
	//先删除v在矩阵中所对应的行
	for (w = i; w < G.vexnum - 1; w++) {
		for (j = 0; j < G.vexnum; j++)
			if (G.arcs[w][j] < MaxInt)
				s++;
		G.arcs[w][j] = G.arcs[w + 1][j];
	}
	for (w = i; w < G.vexnum - 1; w++) {
		for (j = 0; j < G.vexnum; j++)
			G.arcs[j][w] = G.arcs[j][w + 1];
	}
	//在顶点集合中删除该顶点
	for (j = i; j < G.vexnum - 1; j++)
		G.vexs[j] = G.vexs[j + 1];
	G.vexnum--;
	G.arcnum -= s;
}

void CreateUDN(AMGraph & G)
{ //建立一个无向网
	int vexnum, arcnum, i;
	VerType V, U;
	ArcType W;
	cout << "请输入所建图的顶点数及边数:" << endl;
	cin >> vexnum >> arcnum;
	cout << "请输入" << vexnum << "个顶点的数据:" << endl;
	for (i = 0; i < vexnum; i++) {
		cin >> V;
		InsertVex(G, V);
	}
	for (i = 0; i < arcnum; i++) {
		cout << "请输入第" << i + 1 << "条边的邻接顶点及权值:" << endl;
		cin >> V >> U >> W;
		InsertArc(G, V,U,W);
	}
}

void DFS_AM(AMGraph G, VerType V)
{//深度优先遍历
	int w, i = LocateVex(G, V);
	cout << V << " ";
	visited[i] = 1;
	for (w = 0; w < G.vexnum; w++) {
		if ((G.arcs[i][w] < MaxInt) && (visited[w] == 0))
			DFS_AM(G, G.vexs[w]);
	}
}

void BFS_AM(AMGraph G, VerType V)
{
}

你可能感兴趣的:(数据结构)