图的遍历 之 广度优先搜索

 

#include <iostream>
#include <algorithm>
#include <iterator>
#include <queue>

using namespace std;    

#define MAX_VERTEX_NUM 10

struct Node
{
	int adjvex;
	struct Node *next;
	int info;
};

typedef struct VNode
{
	char data;
	Node *first;
}VNode, AdjList[MAX_VERTEX_NUM];

struct Graph 
{
	AdjList vertices;
	int vexnum, arcnum;
};

int visited[MAX_VERTEX_NUM];

int locateVex(Graph G, char u)
{
	int i;
	for (i = 0; i < G.vexnum; i++)
	{
		if (u == G.vertices[i].data)
			return i;
	}

	if (i == G.vexnum)
	{
		printf("Error u!\n");
		exit(1);
	}

	return 0;
}

void createGraph(Graph &G)
{
	int i, j, k, w;
	char v1, v2, enter;

	Node *p;
	printf("input vexnum & arcnum:\n");
	scanf("%d", &G.vexnum);
	scanf("%d", &G.arcnum);
	printf("input vertices:\n");
	for (i = 0; i < G.vexnum; i++)
	{
		scanf("%c%c", &enter, &G.vertices[i].data);
		G.vertices[i].first = NULL;
	}

	printf("input Arcs(v1, v2, w):\n");
	for (k = 0; k < G.arcnum; k++)
	{
		scanf("%c%c", &enter, &v1);
		scanf("%c%c", &enter, &v2);
		scanf("%d", &w);
		i = locateVex(G, v1);
		j = locateVex(G, v2);
		p = (Node *)malloc(sizeof(Node));
		p->adjvex = j;
		p->info = w;
		p->next = G.vertices[i].first;
		G.vertices[i].first = p;
	}
}

void BFSTraverse(Graph &G)

{

	queue<int> Q;

	for(int v = 0; v < G.vexnum; ++v)
		visited[v] = false;

	for(int v = 0;v < G.vexnum; ++v)
	{
		if(!visited[v])
		{
			Q.push(v);
			while(!Q.empty())
			{
				int u = Q.front();
				Q.pop();
				visited[u]=true;
				printf("->%c",G.vertices[u].data);//visit一下
				for(Node *w= G.vertices[u].first; w ; w = w->next)
					if(!visited[w->adjvex])
						Q.push(w->adjvex);
			}//while
		}//if
	}

}//BFSTraverse

int main()
{
	Graph G;
	createGraph(G);
	BFSTraverse(G);
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/alexingcool/article/details/8038357
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞