图的基本操作(插入、删除、查找、遍历)

#include <iostream>
using namespace std;
#define MaxInt 32767
#define MaxNum 100
#define MaxSize 100
bool visited[MaxNum];
typedef char VertexType;//顶点数据类型为字符型
typedef int ArcType;//边的权值为整形

typedef struct
{
	VertexType vexs[MaxNum];//定点表
	ArcType arcs[MaxNum][MaxNum];//邻接举证
	int vexnum, arcnum;//图的顶点和边数
}MGraph;
MGraph G;
typedef struct
{
	int *base;
	int front, rear;
}SQueue;
void InitQueue(SQueue & Q)
{//构造一个空队列Q并分配最大容量
	Q.base = new int[MaxSize];
	if (!Q.base)//分配失败
		exit(0);
	Q.front = Q.rear = 0;//头指针和尾指针为0,队列为空
}
void EnQueue(SQueue &Q, int e)
{//插入新元素e为Q的对位元素
	if ((Q.rear + 1) % MaxSize == Q.front)// //尾指针在循环意义上加1后等于头指针,表明队满
		return ;
	Q.base[Q.rear] = e;//新元素插入队尾
	Q.rear = (Q.rear + 1) % MaxSize;//队尾元素+1
}
void DEQueue(SQueue &Q, int &e)
{//删除Q的对头元素,用e返回其值
	if (Q.front == Q.rear)//元素为空
		return ;
	e = Q.base[Q.front];//保存对头元素
	Q.front = (Q.front + 1) % MaxSize;//对头指针+1
}
int QueueEmpty(SQueue &Q)
{
	if (Q.front == Q.rear)
		return 1;
	else
		return 0;
}
int LocateVex(MGraph G, int b)
{//判断顶点在第几个位置
	for (int i = 0; i < G.vexnum; i++)
		if (G.vexs[i] == b)
			return i;
}
void CreateUDN(MGraph &G)
{//采用邻接矩阵表示法创建无向网
	cout << "请输入顶点的个数:\n";
	cin >> G.vexnum;
	cout << "请输入边的条数:\n";
	cin >> G.arcnum;
	int v1, v2;
	cout << "依次输入顶点的信息:\n";
	for (int i = 0; i < G.vexnum; i++)
		cin >> G.vexs[i];
	for (int i = 0; i < G.arcnum; i++)
		for (int j = 0; j < G.arcnum; j++)
			G.arcs[i][j] = 0;
	for (int i = 0; i < G.arcnum; i++)
	{
		cout << "请输入一条边依附的顶点:";
		cin >> v1 >> v2;
		G.arcs[v1][v2] = 1;
		G.arcs[v2][v1] = 1;
	}
}
void DFS(MGraph G, int v)
{
	cout << G.vexs[v];
	visited[v] = 1;
	for (int i = 0; i < G.vexnum; i++)
		if ((G.arcs[v][i] ==1) && (visited[i]==0))
			DFS(G, i);
}
void BFS(MGraph G, int v)
{
	int Q[MaxSize];
	int front = -1, rear = -1;
	cout << G.vexs[v];
	visited[v] = 1;
	Q[++rear] = v;
	while (front != rear)
	{
		v = Q[++front];
		for (int j = 0; j < G.vexnum; j++)
		{
			if (G.arcs[v][j] == 1 && visited[j] == 0)
			{
				cout << G.vexs[j];
				visited[j] = 1;
				Q[++rear] = j;
			}
		}
	}
}
int main()
{
	CreateUDN(G);
	cout << "DFS:" << endl;
	DFS(G, 1);
	for (int a = 0; a < MaxNum; a++)
		visited[a] = 0;
	cout << "\nBFS:" << endl;
	BFS(G, 1);
	return 0;
}
posted @ 2019-10-28 15:23  如梦山河乀  阅读(221)  评论(0编辑  收藏  举报