按广度优先非递归遍历连通图G

#include<iostream>
using namespace std;
#define mvnum 50//最大顶点数
#define maxsize 50//队列大小
typedef int arctype;//假设边的权值类型为整型
typedef char vertextype;//设顶点的数据类型为字符型
typedef int elemtype;
typedef struct
{
	vertextype vexs[mvnum];//顶点表
	arctype arcs[mvnum][mvnum];//邻接矩阵
	int vexnum, arcnum;
}amgraph;
typedef struct
{
	elemtype* base;
	int front;
	int rear;
}sqqueue;
bool initqueue(sqqueue& q)
{
	q.base = new elemtype[maxsize];
	if (!q.base)
	{
		exit(-1);
	}
	q.front = q.rear=0;
	return 1;
}
bool enqueue(sqqueue& q,elemtype e)
{
	if ((q.rear + 1) % maxsize == q.front)
	{
		return 0;
	}
	q.base[q.rear] = e;
	q.rear = (q.rear + 1) % maxsize;
	return 1;
}
bool dequeue(sqqueue& q, elemtype& e)
{
	if (q.front == q.rear)
	{
		return 0;
	}
	e = q.base[q.front];
	q.front = (q.front + 1) % maxsize;
	return 1;
}
bool emptyqueue(sqqueue q)
{
	if (q.front == q.rear)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
int firstadjvex(amgraph G, int u)
{
	for (int i = 0;i < G.vexnum;i++)
	{
		if (G.arcs[u][i] == 1)
		{
			return i;
		}
	}
	return -1;
}
int nextadjvex(amgraph G, int u, int w)//查找图G中第u行第w列后在邻接矩阵值为1的下标
{
	for (int i = w+1;i < G.vexnum;i++)
	{
		if (G.arcs[u][i] == 1)
		{
			return i;
		}
	}
	return -1;
}
void BFS(amgraph G, int v)
{
	int visited[mvnum]={0};
	cout << v;
	visited[v] = 1;
	sqqueue Q;
	initqueue(Q);
	enqueue(Q, v);
	while (!emptyqueue(Q))
	{
		int u;
		dequeue(Q,u);
		for (int w =firstadjvex(G,u);w >= 0;w=nextadjvex(G,u,w))
		{
			if (!visited[w])
			{
				cout << w;
				visited[w] = 1;
				enqueue(Q, w);
			}
		}
	}
}
int main()
{
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值